library(dplyr)
library(tidyr)
library(lme4)
library(marked)

danaid <-read.csv("tagging.csv")

danaid$YearCode <-factor(paste(danaid$Season,danaid$Code))
danaid$Date <-as.Date(danaid$Date,format="%d/%m/%Y")
danaid$Month <-factor(months(danaid$Date))
danaid$Species2 <-danaid$Species
danaid <- danaid %>% separate(Species2, c("Genus","Sp"))

tag <-danaid[danaid$Status=="Tag",]


########################

#Species ratio within Euploea in forested valleys

euploea <-danaid[danaid$Status %in% c("Tag","Recapture")& danaid$Site_type=="Forested valley"&
                   danaid$Species %in% c("Euploea midamus","Euploea core"),] %>% 
  group_by(Site_abb,Season,Date) %>% count(Date,Species)
euploea <-euploea %>% group_by(Site_abb,Season,Date) %>% dplyr::mutate(Percentage= n/sum(n))
euploea$SiteYear <-paste(euploea$Site_abb,euploea$Season)
euploea$SiteDate <-paste(euploea$Site_abb,euploea$Date)

#Only retain sampling days with >20 individuals captured
Dates <-danaid[danaid$Status %in% c("Tag","Recapture")& danaid$Site_type=="Forested valley"&
                 danaid$Species %in% c("Euploea midamus","Euploea core"),] %>% 
  group_by(Site_abb,Season,Date) %>% count(Date)
Dates <-Dates[Dates$n >20,]
Dates$SiteDate <-paste(Dates$Site_abb,Dates$Date)
euploea <-euploea[euploea$SiteDate %in% Dates$SiteDate,]

#Only retain aggregations with >2 days of sampling
Years <-Dates %>% group_by(Site_abb,Season) %>% count(Season)
Years <-Years[Years$n>2,]
Years$SiteYear <-paste(Years$Site_abb,Years$Season)
euploea <-euploea[euploea$SiteYear %in% Years$SiteYear,]

euploea2 <-euploea[euploea$Species=="Euploea core",]
euploea2 <-euploea2 %>% group_by(Site_abb,Season) %>% dplyr::mutate(Date2=as.numeric(Date-first(Date))+1)

#Binomial GLMM
md <-glmer(data=euploea2[!(euploea2$SiteYear %in% c("KSCP1 2022","SLS 2023")),], 
           Percentage~ Date2 + (1+Percentage|SiteYear), family=binomial)
summary(md)


########################

#Sex ratio changes of Euploea midamus & Euploea core in forested valleys

euploeab <-danaid[danaid$Status %in% c("Tag","Recapture")& danaid$Site_type=="Forested valley"&
                   danaid$Species %in% c("Euploea midamus","Euploea core"),] %>% 
  group_by(Site_abb,Season,Date) %>% count(Date,Species,Sex)
euploeab <-euploeab %>% group_by(Site_abb,Season,Date,Species) %>% dplyr::mutate(Percentage= n/sum(n))
euploeab$SiteDateSp <-paste(euploeab$Site_abb,euploeab$Date,euploeab$Species)
euploeab$SiteYearSp <-paste(euploeab$Site_abb,euploeab$Season,euploeab$Species)

#Only retain sampling days with >20 individuals captured per species
Dates <-danaid[danaid$Status %in% c("Tag","Recapture")& danaid$Site_type=="Forested valley"&
                 danaid$Species %in% c("Euploea midamus","Euploea core"),] %>% 
  group_by(Site_abb,Season,Date,Species) %>% count(Date)
Dates <-Dates[Dates$n >20,]
Dates$SiteDateSp <-paste(Dates$Site_abb,Dates$Date,Dates$Species)
euploeab <-euploeab[euploeab$SiteDateSp %in% Dates$SiteDateSp,]

#Only retain aggregations with >2 days of sampling
Years <-Dates %>% group_by(Site_abb,Season,Species) %>% count(Season)
Years <-Years[Years$n>2,]
Years$SiteYearSp <-paste(Years$Site_abb,Years$Season,Years$Species)
euploeab <-euploeab[euploeab$SiteYearSp %in% Years$SiteYearSp,]

euploeab <-euploeab[complete.cases(euploeab[,c("Sex")]),]

euploeab2 <-euploeab[euploeab$Sex=="M",]
euploeab2 <-euploeab2 %>% group_by(Site_abb,Season,Species) %>% dplyr::mutate(Date2=as.numeric(Date-first(Date))+1)

#Binomial GLMM
md <-glmer(data=euploeab2, Percentage~ Date2+Species + (1+Percentage|SiteYearSp), family=binomial)
summary(md)



########################


# Wing condition
wing <-danaid[danaid$Status %in% c("Tag","Recapture") & danaid$Season!="2021"& 
                   danaid$Month %in% c("October","November","December","January","February") ,] %>%
  group_by(Date,Wing,Genus) %>% count()

#Create "Date2" to remove year
wing$Date <-as.Date(wing$Date,origin="1970-01-01")
wing$Date2 <-as.Date(format(wing$Date,format="%b-%d"),format="%b-%d")  #Remove year
wing$Date2 <-ifelse(format(wing$Date2,format="%m") %in% c("01","02"),wing$Date2+365,wing$Date2)  #Adjust Jan & Feb records
wing$Date2 <-as.Date(wing$Date2,origin="1970-01-01")

Weeks <-data.frame(Date = seq(as.Date("2025-10-01"), as.Date("2026-02-24"), by="days"),
                   Week = rep(seq(from=1, to=21, by=1), each=7))
wing$Week <-NA
for(x in 1:nrow(wing)) {
  if(wing$Date2[x] %in% Weeks$Date){
    n <-which(Weeks$Date ==wing$Date2[x])
    wing$Week[x] <-Weeks$Week[n]
  } else {
    next
  }
}

wing <-wing %>% group_by(Week,Genus,Wing) %>% dplyr::summarize(n=sum(n))
wing <-wing[complete.cases(wing[,c("Wing")]),] 
wing$WeekGenus <-paste(wing$Week,wing$Genus)

#Only retain weeks with >20 individuals captured
wing2 <-wing %>% group_by(Week,Genus) %>% dplyr::summarize(Total=sum(n))
wing2 <-wing2[wing2$Total>20,]
wing2$WeekGenus <-paste(wing2$Week,wing2$Genus)
wing <-wing[wing$WeekGenus %in% wing2$WeekGenus,]

wing <-wing[wing$Wing %in% c("1","2","3","4","5"),]


Weeks2 <-Weeks %>% group_by(Week) %>% dplyr::summarize(Date=first(Date))
wing$Date <-NA
for(x in 1:nrow(wing)) {
  if(wing$Week[x] %in% Weeks2$Week) {
    n <-which(Weeks2$Week==wing$Week[x])
    wing$Date[x] <-Weeks2$Date[n]
  } else {
    next
  }
}
wing$Date <-as.Date(wing$Date,origin="1970-01-01")

#Proportion of individuals with wing condition score=1
wing <- wing %>% spread(key=Wing, value=n) %>% gather(key=Wing, value=n, -c(Week,Date,Genus,WeekGenus)) %>%
  replace_na(list(n=0))   #Adding zeros to missing wing condition categories
wing <-wing %>% group_by(Date,Genus) %>% dplyr::mutate(Proportion=first(n)/sum(n))

#Binomial GLM
wing3 <-wing[wing$Wing=="1",]
md <-glm(data=wing3,Proportion~Week*Genus, family="binomial")
summary(md)



########################

#Jolly Seber model for aggregation size estimates
#Using Site CMWP1 in season 2021-22 as an example here

cmwp1 <-danaid[danaid$Season==2021 & danaid$Site_abb=="CMWP1" & danaid$Status %in% c("Tag","Recapture"),]
cmwp1$Detect <-1
Dates <-data.frame(Date=c("2022-01-04","2022-01-08","2022-01-09","2022-01-11","2022-01-15","2022-01-23"),
                   Event=c("E1","E2","E3","E4","E5","E6"))
Dates$Date <-as.Date(Dates$Date,format="%Y-%m-%d")
for(i in 1:nrow(cmwp1)){
  if(cmwp1$Date[i] %in% Dates$Date){
    n <-which(Dates$Date==cmwp1$Date[i])
    cmwp1$Event[i] <-Dates$Event[n]
  } else {
    next
  }
}

# Capture history
cmwp1 <-cmwp1[complete.cases(cmwp1[,c("Code")]),]
cmwp1.ch <-cmwp1 %>% spread(Event,Detect,fill=0) %>% group_by(Code) %>% dplyr::summarize(E1=sum(E1),E2=sum(E2),E3=sum(E3),E4=sum(E4),E5=sum(E5),E6=sum(E6)) %>%
  unite("ch", 2:tail(names(.),1), sep = "")

#For CMWP1 in season 2021-22, run the following to model by species
#Otherwise, skip the following three lines if modelling the whole aggregation
cmwp1.ch <-merge(x=cmwp1.ch,y=cmwp1[1:1951,c(1,8)],by.x="Code",by.y="Code",all.x=T)
cmwp1.ch <-cmwp1.ch[cmwp1.ch$Species %in% c("Euploea midamus"),]      #Change the name for other dominant species: "Euploea core","Ideopsis similis"
cmwp1.ch <-cmwp1.ch[,1:2]

# Model
cmwp1.js.proc <- process.data(cmwp1.ch,model="JS")
cmwp1.js.ddl <- make.design.data(cmwp1.js.proc)  

fit.js.cmwp1.models <- function(){
  Phi.dot <- list(formula=~1)
  Phi.time <- list(formula=~time)  
  p.dot <- list(formula=~1)
  pent.dot <- list(formula=~1)
  pent.time <- list(formula=~time)
  N.dot <- list(formula=~1)
  cml <- create.model.list(c("Phi","p", "pent", "N"))
  results <- crm.wrapper(cml, data = cmwp1.js.proc, ddl = cmwp1.js.ddl,
                         external = FALSE, accumulate = FALSE, hessian = TRUE)
  return(results)
}
cmwp1.js.models <- fit.js.cmwp1.models()
cmwp1.js.models

#Depends on model selection based on AIC
#Use the following if model 4 [Phi(~time)p(~1)pent(~time)N(~1)] is the best one
cmwp1.js.models[[4]]
cmwp1.js.predicted <- predict(cmwp1.js.models[[4]]) 
cmwp1.js.predicted
N.derived <- data.frame(occ = c(1:6),   # 6 sampling events
                        Phi = c(cmwp1.js.predicted$Phi$estimate, NA), 
                        Nsuper = rep(cmwp1.js.predicted$N$estimate + nrow(cmwp1.ch), 6),   #Nsuper estimate + number of marked animals
                        pent = c(1-sum(cmwp1.js.predicted$pent$estimate), cmwp1.js.predicted$pent$estimate))   #Sum of all pent must be 1

#Use the following if model 2 [Phi(~1)p(~1)pent(~time)N(~1)] is the best one
cmwp1.js.models[[2]]
cmwp1.js.predicted <- predict(cmwp1.js.models[[2]])
cmwp1.js.predicted
N.derived <- data.frame(occ = c(1:6),    # 6 sampling events
                        Phi = c(rep(cmwp1.js.predicted$Phi$estimate,5), NA), 
                        Nsuper = rep(cmwp1.js.predicted$N$estimate + nrow(cmwp1.ch), 6),   #Nsuper estimate + number of marked animals
                        pent = c(1-sum(cmwp1.js.predicted$pent$estimate), cmwp1.js.predicted$pent$estimate))   #Sum of all pent must be 1

#Calculate N
N.derived$N <- NA
N.derived$N[1] <- (N.derived$Nsuper[1] * N.derived$pent[1])
for(i in 2:nrow(N.derived)){
  N.derived$N[i] <- (N.derived$N[i-1]*N.derived$Phi[i-1]) + (N.derived$Nsuper[i] * N.derived$pent[i])
}
N.derived




