
rm(list=ls())

library(tidyverse)
library(survival)
library(GGally)
library(ggfortify)
library(lme4)
library(lubridate)
library(gridExtra)
library(car)
library(multcomp)
library(DHARMa)

########################################################################################################################################################################
################################################ Analysis of calf mortality according to calf and maternal traits ################################################
mothinfo<-read.csv("Anon_Data_SR.csv")

#### format all the variables correctly
mothinfo$anon_id<-as.character(mothinfo$anon_id)
mothinfo$mother_anon_id<-as.character(mothinfo$mother_anon_id)
mothinfo$dead_4_5<-as.factor(as.character(mothinfo$dead_4_5))
mothinfo$Decade_birth<-as.factor(as.character(mothinfo$Decade_birth))
mothinfo$bo_cat<-as.factor(as.character(mothinfo$bo_cat))

modfinal<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))

### assess and plot fit of model using DHARMa
simulationOutput <- simulateResiduals(fittedModel = modfinal, n = 250)
plot(simulationOutput)

####  test the terms of the model 
nullcatmotha<-glmer(dead_4_5 ~ bo_cat + sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
nullcatbo<-glmer(dead_4_5 ~ moth_age_lim_sc  +  sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
nullcatsex<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat +  month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
nullcatmonthb<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
nullcatmo<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex + month_birth + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
nullcatdecade<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex + month_birth + moth_origin:moth_time_capture + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))

### 

##### results (using anova method="ML"): 
### mothers age marginal (X2= 3.68, d.f=1, p=0.0552)
## bo_cat sig (X2= 10.86, d.f=2, p<0.01)
## sex not sig (X2= 1.23, d.f=1, p=0.2675)
## month birth sig (X2=4.19, d.f=1, p<0.05)
## mother origin not sig (X2=1.8627, d.f=1, p=0.1723)
## decade birth sig (X2=20.5, d.f=3, p<0.001)

### test the significance within a term - different levels 
summary(glht(modfinal, linfct = mcp(bo_cat = "Tukey")), test=adjusted("holm"))
### 3 sig diff from both 1 and 2, but 1 and 2 not sig diff from eachother
summary(glht(modfinal, linfct = mcp(Decade_birth= "Tukey")), test=adjusted("holm"))
### 2000 sig diff from all other decades, but no other decades differ from eachother

## check the correlation between terms
# vif(modfinal)
#                               GVIF      Df       GVIF^(1/(2*Df))
# moth_age_lim_sc               1.942673  1        1.393798
# bo_cat                        1.467895  2        1.100712
# sex                           1.004876  1        1.002435
# month_birth                   1.006603  1        1.003296
# Decade_birth                  1.050147  3        1.008188
# moth_origin:moth_time_capture 1.414652  1        1.189391

#############################################################################################################################################
######################## try model in restricted datasets, to check that effects are consistent ###########################################
###########################################################################################################################################
################################################# include only calves who's mother survived ################################################
mothsurvived<- mothinfo %>%  filter(is.na(age_moth_death)| age_moth_death>=4)
modorphan<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothsurvived, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
##### conclusions very similar

## Not appropriate to include mothers id as very few repeats, but check it doesn't make a huge difference to the model fit 
# (987 levels across n= 1947)
finmodmothid<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location) + (1|mother_anon_id), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
nullmodmothid<-glmer(dead_4_5 ~ bo_cat + sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location) + (1|mother_anon_id), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
##### conclusions very similar, mother's age marginal

### check for non-linear effects of mother's age 
modfinalmasq<-glmer(dead_4_5 ~ moth_age_lim_sc  + moth_age_lim_sq + bo_cat + sex + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))

### quad/cub terms of mother's age do not improve fit
#                   df     AIC       BIC 
# modfinal          11    1073.600   1134.914
# modfinalmasq      12    1075.334   1142.223

### any interactions? - could expect that effects of mother or calf age may be diff in  males and females? 
modfinalint1<-glmer(dead_4_5 ~ moth_age_lim_sc*sex  + bo_cat + month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))
modfinalint2<-glmer(dead_4_5 ~ moth_age_lim_sc  + bo_cat + sex*month_birth + moth_origin:moth_time_capture + Decade_birth + (1|combined_location), family=binomial(link="logit"),  data=mothinfo, control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=100000)))

#                 df    AIC       BIC 
# modfinal        11    1073.60   1134.914
# modfinalint1    12    1075.59   1142.478
# modfinalint2    12    1075.54   1142.429
### interactions do not improve model fit 

############################################ PLOT the relationships
###################################################################################################################################################
########################### Figure 1 : survival curve first 10 years and age specific survival of MTE eles and amboseli #############################
captives<-read.csv("Anon_Capt_SR2.csv")

survcurv<- survfit(Surv(lifespan, as.numeric(censored))~Sex, data=captives) ## 2962 captive borns,female n= 1449, male n=1513

### survival curve just first 10 years 
surv10 <- ggsurv(survcurv, CI=TRUE, plot.cens=FALSE, size.est=1, size.ci=0.5, surv.col=c("#3B3B3B", "#E69F00")) + xlim(0,10) + ylim(0.60, 1.00)  +
  theme(axis.title=element_text(size=22), axis.text=element_text(size=18),panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  theme(legend.position="none") +
  geom_vline(xintercept = 4, linetype=4, size=0.75) + geom_vline(xintercept = 5.5, linetype=4, size=0.75) +
  xlab("Age (years)") + ylab("Cumulative Survival") + 
  geom_text(label="(a)", x = -1.3, y=1.05, size = 8) +
  geom_text(label="n=2,962", x = 9, y=1.04, size = 6)+
  coord_cartesian( ylim = c(0.6, 1.02), clip = 'off' ) 

## plot age specific survival (Sx) 
### using rounded ages

captives$lifespan.int<-round(captives$lifespan)

survcurvint<- survfit(Surv(lifespan.int, as.numeric(censored))~Sex, data=captives)  ## survival curve with age as an integer

intsurv<-fortify(survcurvint) ### converts model to dataframe
intsurv<-intsurv[,c(1,5,6,9)] ## keep the relevant info (age, survival prob, sex) + upper and lower CI 

for(i in 1:length(intsurv$time))  {
  intsurv$agesurv[i] <- intsurv$surv[i+1]/intsurv$surv[i]### age specific survival rather than cumulative 
}                                                        ### calculated as the survival at t+1/survival at t 

intsurv$mort<-1-intsurv$agesurv    ## # get mortality rate rather than survival rate 
intsurv<-plyr::rename(intsurv, c("strata"="Sex")) 

cbPalette <- c("#E69F00", "#3B3B3B")
intsurv$Sex <- relevel(intsurv$Sex, ref="Male")

intsurv<-subset(intsurv, time<=10)
surv2 <- ggplot(intsurv, aes(time, mort, fill=Sex))+ geom_point(size=4, colour="black", pch=21, stroke=1) + 
  xlab("Age (years)") + ylab("Mortality Rate") +
  ylim(0, 0.13) +
  theme(axis.title=element_text(size=22), axis.text=element_text(size=18),panel.background = element_blank(), axis.line = element_line(colour = "black"))+ scale_fill_manual(values=cbPalette) +
  theme(legend.position="none") + 
  geom_text(label="(b)", x = -1.3, y=0.13, size = 8) +
  geom_text(label="n=2,962", x = 9, y=0.13, size = 6) +
  coord_cartesian( ylim = c(0, 0.13), clip = 'off' ) +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10))

############################## have a look at how mort rates in Amboseli data compare to ours (taken from lifetables in Moss et al 2011, box 6.1 p81)

amboseli<-read.csv("calf_mort_amboseli.csv")
amboseli<-amboseli %>% mutate(Sex= dplyr::recode(Sex, "M" = "Males", "F"="Females"))
amboseli$Sex <- relevel(amboseli$Sex, ref="Males")

### plot amboseli rates

surv3 <- ggplot(amboseli, aes(Age, Mortality.Rate, fill=Sex))+ geom_point(size=4, colour="black", pch=21, stroke=1) + 
  xlab("Age (years)")+ ylim(0, 0.13) +
  theme(axis.title=element_text(size=22), axis.text=element_text(size=18),
        panel.background = element_blank(), axis.line = element_line(colour = "black"),  axis.title.y=element_blank())+
  scale_fill_manual(values=cbPalette) +
  theme(legend.title=element_text(size=22),legend.text=element_text(size=16), legend.position = c(0.80,0.75), legend.background = element_blank()) +
  geom_text(label="(c)", x = -1.2, y=0.13, size = 8) +
  geom_text(label="n=1,794", x =9, y=0.13, size = 6) +
  coord_cartesian( ylim = c(0, 0.13), clip = 'off' ) +
  scale_x_continuous(breaks = scales::pretty_breaks(n = 10)) 

grid.arrange(surv10, surv2, surv3, nrow=1, ncol=3)
dev.print(tiff, "Fig_1.tiff", res=600, height=4, width=13, units="in", compression="lzw")


############################################################################################################################################
########################## Figure 2: survival probability according to calf and mother traits in raw data and predicted ################

################### predict mortality from simplified model according to month of birth  
modpred2<-glm(dead_4_5 ~ moth_age_lim  + bo_cat + sex + month_birth + Decade_birth, family=binomial(link="logit"),  data=mothinfo)

## create a new dataset for predictions to be made onto
### hold other traits constant- at reasonably average values where we can 
### predict for an individual: female, 1st birth order category, born in the 90s, to a 30 year old mother
newdata2 <- expand.grid(bo_cat=1, sex=("F"), month_birth=seq(1:12), Decade_birth=1990, moth_age_lim=30)

newdata2$Decade_birth<-as.factor(newdata2$Decade_birth)
newdata2$bo_cat<-as.factor(newdata2$bo_cat)

Preds2 <- predict(modpred2, newdata2,  type="response", se.fit=TRUE)
predata2<- cbind(Preds2, newdata2)

### plot averages and predicted values according to birth month

############### summarise mortality rate according to month of birth in raw data
deadprop<-mothinfo %>% dplyr::group_by(month_birth) %>% dplyr::summarise(prop = mean(as.numeric(dead_4_5)),
                                                                         se=sd(as.numeric(dead_4_5))/sqrt(n()))
deadprop$prop<-deadprop$prop-1
predata2$prop<-predata2$fit

Birth_month <- ggplot(predata2, aes(x=month_birth, y=prop, fill="red")) + geom_ribbon(aes(ymin=prop-se.fit, ymax=prop+se.fit), fill='#3B3B3B', alpha=0.3)  +
  geom_line(size=1, colour="#E69F00") + ylab("Mortality Rate") + xlab("Birth month") + 
  geom_errorbar(data=deadprop, aes(ymin=prop-se, ymax=prop+se), width=0.3, size=0.4) +
  geom_point(data=deadprop, aes(group=month_birth), size=4, colour="black", pch=21, stroke=1, fill="#3B3B3B") +
  theme(axis.title=element_text(size=22),axis.text=element_text(size=18),panel.background = element_blank(), 
        axis.line = element_line(colour = "black")) + scale_fill_viridis_d(begin = 0.1, end = 0.7, option="D") +
  theme(legend.position="none") + scale_x_continuous(breaks = scales::pretty_breaks(n = 12))+
  geom_text(label="(a)", x = -0.4, y=0.14, 
            size = 8) +
  coord_cartesian(xlim = c(1, 12), 
                  ylim = c(0.01, 0.14),
                  clip = 'off') 

################  summarise mortality rate by birth order in raw data
tabprop<-mothinfo %>% dplyr::group_by(bo_cat) %>% dplyr::summarise(prop = mean(as.numeric(dead_4_5)),
                                                                    se=sd(as.numeric(dead_4_5))/sqrt(n()))
tabprop$prop<-tabprop$prop-1

### specify what each category level refers to:
tabprop <- tabprop %>% mutate(bo_cat = dplyr::recode(bo_cat, "1"="1", "2"="2-3", "3"="4+"))

Birth_order<-ggplot(tabprop, aes(x=bo_cat, y=prop))  + 
  geom_errorbar(data=tabprop, aes(ymin=prop-se, ymax=prop+se), width=0.1, size=0.4) +
  geom_point(size=4, colour="black", pch=21, stroke=1, fill="#3B3B3B") +
  theme(axis.title=element_text(size=22),axis.text=element_text(size=18),panel.background = element_blank(), 
        axis.line = element_line(colour = "black"),  axis.title.y=element_blank()) + 
  xlab("Birth order") +
  geom_text(label="a", x = 1, y=0.112,  ### show the statistical differences between levels from earlier tukey test
            size = 6, colour="#E69F00") +
  geom_text(label="a", x = 2, y=0.119, 
            size = 6, colour="#E69F00") +
  geom_text(label="b", x = 3, y=0.075, 
            size = 6, colour="#E69F00") +
  geom_text(label="(c)", x = 0.17, y=0.14, 
            size = 8) +
  geom_text(label="n=1947", x = 3, y=0.14, 
            size = 6) +
  coord_cartesian(xlim = c(1, 3),
                  ylim = c(0.01, 0.14),
                  clip = 'off') 



############################ plot probability of  over time according to birth decade 

decprop<-mothinfo %>% dplyr::group_by(Decade_birth) %>% dplyr::summarise(prop = mean(as.numeric(dead_4_5)),
                                                                         se=sd(as.numeric(dead_4_5))/sqrt(n()))

decprop <- decprop %>% mutate(Decade_birth = dplyr::recode(Decade_birth, "1"="1970-79", "2"="1980-89", 
                                                           "3"="1990-99", "4"="2000-13"))
decprop$prop<-decprop$prop-1

Birth_decade<-ggplot(decprop, aes(x=Decade_birth, y=prop, fill="red"))+ xlab("Birth decade") + 
  geom_errorbar(data=decprop, aes(ymin=prop-se, ymax=prop+se), width=0.1, size=0.4) +
  geom_point(data=decprop, aes(group=Decade_birth), size=4, colour="black", pch=21, stroke=1, fill="#3B3B3B") +
  theme(axis.title=element_text(size=22),axis.text=element_text(size=18),panel.background = element_blank(), 
        axis.line = element_line(colour = "black"),  axis.title.y=element_blank()) + 
  theme(legend.position="none") +
  geom_text(label="(b)", x = 0.08, y=0.14, 
            size = 8) +
  geom_text(label="a", x = 1, y=0.148,  ## show statistical difference between levels within group
            size = 6, colour="#E69F00") +
  geom_text(label="a", x = 2, y=0.115, 
            size = 6, colour="#E69F00") +
  geom_text(label="a", x = 3, y=0.119, 
            size = 6, colour="#E69F00") +
  geom_text(label="b", x = 4, y=0.045, 
            size = 6, colour="#E69F00")+
  coord_cartesian( ylim = c(0.01, 0.14),
                   clip = 'off' ) 

### plot these together 
grid.arrange(Birth_month, Birth_decade, Birth_order, nrow=1, ncol=3)

dev.print(tiff, "Fig_2.tiff", res=600, height=4, width=13, units="in", compression="lzw")
