###### This code recreates all of the figures in the paper "Epidemiologically-based strategies for the detection of emerging plant pathogens".
###### Another set of code ("hostVectorAnalysis.R") has been developed to allow manipulation of the vector prevalence estimates used for predicting early stage host and vector prevalences.


library(tidyverse) # for data manipulation
library(ggthemes) # for plotting
library(scales) # for plotting
library(viridis) # for plotting
library(RColorBrewer) # for plotting
library(directlabels) # for plotting
library(patchwork) #  for plotting
library(ggtext) # for text in plots

dir.create("plots") # create new directory to save plots

##### Surveillance parameters
percentile <- 0.90 # percentile as a proportion
testSensHost <- 1 # sensitivity of detection method in hosts (assume detection method in hosts has perfect specificity)
maxPrev <- 0.01 # maximum acceptable prevalence if no detections
sampInterval <- 365/4 # interval between sampling rounds (days)

##### Epidemiological parameters
rMinXf <- 0.0122 - 0.00747 # minimum r (per day) for X. fastidiosa in olive
rMaxXf <- 0.0122 + 0.00747 # maximum r (per day) for X. fastidiosa in olive
rEst <- mean(c(rMinXf,rMaxXf)) # mean r (per day) for X. fastidiosa in olive

lambdaMinXf <- 141 # earliest reported time of symptoms for X. fastidiosa in olive
lambdaMaxXf <- 627 # upper quartile of time of symptoms for X. fastidiosa in olive
asympPeriod <- 313 # median duration of asymptomatic period for X. fastidiosa in olive

##### Visualising effect of asymptomatic period -----

logisticGrowth <- function(init,rEst,offset,time){
  ((init*exp(rEst*(time-offset)))/(1-init+init*exp(rEst*(time-offset))))
}

maxTime <- 6

logGrowthPlotXf <- data.frame(time = seq(0,365*maxTime),
                              truePrev = NA,
                              visPrev = NA)

logGrowthPlotXf$truePrev <- logisticGrowth(1e-03,rEst,0,logGrowthPlotXf$time)
logGrowthPlotXf$visPrev <- logisticGrowth(1e-03,rEst,asympPeriod,logGrowthPlotXf$time)

lineTime <- 365
maxTime <- 4

x1Horiz <- lineTime
x2Horiz <- logGrowthPlotXf$time[which(logGrowthPlotXf$visPrev>logGrowthPlotXf$truePrev[which(logGrowthPlotXf$time==lineTime)])][1]
yHoriz <- logGrowthPlotXf$truePrev[which(logGrowthPlotXf$time==lineTime)]
xVert <- mean(c(x1Horiz,x2Horiz))
y1Vert <- logGrowthPlotXf$visPrev[which(logGrowthPlotXf$time==xVert)]
y2Vert <- logGrowthPlotXf$truePrev[which(logGrowthPlotXf$time==xVert)]

plotColours <- c("true prevalence" = viridis(2)[1],
                 "apparent prevalence" = viridis(2)[2])

logGrowthXfPlot <- ggplot(data=logGrowthPlotXf,aes(x=time)) +
  geom_line(aes(y=truePrev, col="true prevalence"),lwd=2) +
  geom_line(aes(y=visPrev, col="apparent prevalence"),lwd=2) +
  geom_segment(aes(x=x1Horiz, y=yHoriz, xend=x2Horiz, yend=yHoriz),
               arrow = arrow(length = unit(0.04, "npc"), angle = 20, type="closed", ends="both"),
               lwd=1) +
  geom_segment(aes(x=xVert, y=y1Vert, xend=xVert, yend=y2Vert),
               arrow = arrow(length = unit(0.04, "npc"), angle = 20, type="closed", ends="both"),
               lwd=1) +
  labs(y="Prevalence",
       col="") +
  scale_x_continuous(name ="Year",
                     breaks = seq(0,365*maxTime,365),
                     labels = seq(0,maxTime,1),
                     limits = c(0,maxTime*365)) +
  scale_colour_manual(values = plotColours) +
  theme_bw(base_size=40) +
  theme(legend.position="top")

asmypPerSympXfPlot <- ggplot(data=logGrowthPlotXf,aes(x=time,y=(logGrowthPlotXf$truePrev/logGrowthPlotXf$visPrev)-1)) +
  geom_line(lwd=2) +
  geom_hline(yintercept =  exp(rEst*asympPeriod), lty=2, lwd=2) +
  labs(y="Asymptomatic trees\n per symptomatic tree") +
  scale_x_continuous(name ="Year",
                     breaks = seq(0,365*maxTime,365),
                     labels = seq(0,maxTime,1),
                     limits = c(0,maxTime*365)) +
  theme_bw(base_size=40)


##### Putting panels together: Figure 1
logGrowthXfPlotPanel <- logGrowthXfPlot +
  labs(tag="A")
asmypPerSympXfPlotPanel <- asmypPerSympXfPlot +
  labs(tag="B")
fig1Plots <- logGrowthXfPlotPanel / asmypPerSympXfPlotPanel
ggsave("plots/fig01.png",fig1Plots,width=15,height=20)
ggsave("plots/fig01.eps",fig1Plots,width=15,height=20)

##### Comparing apparent and true prevalence for different pathogens -----

rMinAshDieback <- 0.0024 # minimum r (per day) for H. fraxineus in ash
rMaxAshDieback <- 0.0024 # maximum r (per day) for H. fraxineus in ash
lambdaMinAshDieback <- 6*7 # minimum duration of asymptomatic period for H. fraxineus in ash
lambdaMaxAshDieback <- 365 # maximum duration of asymptomatic period for H. fraxineus in ash
rMinSOD <- 0.00111 # minimum r (per day) for P. ramorum in rhododendron
rMaxSOD <- 0.0054 # maximum r (per day) for P. ramorum in rhododendron
lambdaMinSOD <- 2 # minimum duration of asymptomatic period for P. ramorum in rhododendron
lambdaMaxSOD <- 4*7 # maximum duration of asymptomatic period for P. ramorum in rhododendron
rMinCanker <- 0.0163 # minimum r (per day) for X. citri in citrus
rMaxCanker <- 0.0204 # maximum r (per day) for X. citri in citrus
lambdaMinCanker <- 7 # minimum duration of asymptomatic period for X. citri in citrus
lambdaMaxCanker <- 107 # maximum duration of asymptomatic period for X. citri in citrus
rMinHLB <- 0.0022 # minimum r (per day) for Ca. Liberibacter asiaticus in citrus
rMaxHLB <- 0.0126 # maximum r (per day) for Ca. Liberibacter asiaticus in citrus
lambdaMinHLB <- 365/2 # minimum duration of asymptomatic period for Ca. Liberibacter asiaticus in citrus
lambdaMaxHLB <- 2*365 # maximum duration of asymptomatic period for Ca. Liberibacter asiaticus in citrus

rAshDieback <- mean(c(rMinAshDieback,rMaxAshDieback)) # mean r (per day) for H. fraxineus in ash
asympAshDieback <- mean(c(lambdaMinAshDieback,lambdaMaxAshDieback)) # mean duration of asymptomatic period for H. fraxineus in ash
rSOD <- mean(c(rMinSOD,rMaxSOD)) # mean r (per day) for P. ramorum in rhododendron
asympSOD <- mean(c(lambdaMinSOD,lambdaMaxSOD)) # mean duration of asymptomatic period for P. ramorum in rhododendron
rCanker <- mean(c(rMinCanker,rMaxCanker))# mean r (per day) for X. citri in citrus
asympCanker <- mean(c(lambdaMinCanker,lambdaMaxCanker)) # mean duration of asymptomatic period for X. citri in citrus
rHLB <- mean(c(rMinHLB,rMaxHLB))# mean r (per day) for Ca. Liberibacter asiaticus in citrus
#asympHLB <- mean(c(lambdaMinHLB,lambdaMaxHLB)) # mean duration of asymptomatic period for Ca. Liberibacter asiaticus in citrus
asympHLB <- 365 # manual adjustment

truePrevFunc <- function(appPrev,r,detLag){
  truePrev <- appPrev*exp(r*detLag)/(1+appPrev*(exp(r*detLag)-1))
  return(truePrev)
}

prevSeq <- seq(0,1,0.001)

logGrowthPlots <- data.frame(visPrev = rep(prevSeq,5),
                             disease = rep(c("OQDS","AshDieback","SOD","CitrusCanker","HLB"),each=(length(prevSeq))),
                             truePrev = NA)
logGrowthPlots$truePrev[which(logGrowthPlots$disease=="OQDS")] <- truePrevFunc(logGrowthPlots$visPrev[which(logGrowthPlots$disease=="OQDS")],rEst,asympPeriod)
logGrowthPlots$truePrev[which(logGrowthPlots$disease=="AshDieback")] <- truePrevFunc(logGrowthPlots$visPrev[which(logGrowthPlots$disease=="AshDieback")],rAshDieback,asympAshDieback)
logGrowthPlots$truePrev[which(logGrowthPlots$disease=="SOD")] <- truePrevFunc(logGrowthPlots$visPrev[which(logGrowthPlots$disease=="SOD")],rSOD,asympSOD)
logGrowthPlots$truePrev[which(logGrowthPlots$disease=="CitrusCanker")] <- truePrevFunc(logGrowthPlots$visPrev[which(logGrowthPlots$disease=="CitrusCanker")],rCanker,asympCanker)
logGrowthPlots$truePrev[which(logGrowthPlots$disease=="HLB")] <- truePrevFunc(logGrowthPlots$visPrev[which(logGrowthPlots$disease=="HLB")],rHLB,asympHLB)

maxPrevVis <- 0.15

logGrowthPlotsNew <- logGrowthPlots %>%
  filter(visPrev<maxPrevVis) %>%
  mutate(label_r = if_else(visPrev == max(visPrev), as.character(disease), NA_character_),
         label_lag = if_else(visPrev == max(visPrev), as.character(disease), NA_character_)) %>%
  mutate(label_r=ifelse(label_r=="AshDieback", paste0("r=",round(rAshDieback,3)), 
                        ifelse(label_r=="CitrusCanker", paste0("r=",round(rCanker,3)), 
                               ifelse(label_r=="HLB", paste0("r=",round(rHLB,3)), 
                                      ifelse(label_r=="OQDS", paste0("r=",round(rEst,3)), 
                                             ifelse(label_r=="SOD", paste0("r=",round(rSOD,3)),
                                                                          label_r))))),
         label_lag=ifelse(label_lag=="AshDieback", paste0("lag=",round(asympAshDieback),"d"), 
                        ifelse(label_lag=="CitrusCanker", paste0("lag=",round(asympCanker),"d"), 
                               ifelse(label_lag=="HLB", paste0("lag=",round(asympHLB),"d"), 
                                      ifelse(label_lag=="OQDS", paste0("lag=",round(asympPeriod),"d"), 
                                             ifelse(label_lag=="SOD", paste0("lag=",round(asympSOD),"d"),
                                                    label_lag))))))

relPrevPlots <- ggplot(data=logGrowthPlotsNew,aes(x=visPrev,y=truePrev,group=disease,colour=disease)) +
  geom_line(lwd=2) + xlim(c(0,maxPrevVis)) +
  labs(x="Prevalence of visual signs", y="Prevalence of infection") + 
  theme_bw(base_size=40) +
  scale_colour_viridis(name = "Disease",
                       breaks = c("OQDS",
                                  "HLB",
                                  "CitrusCanker",
                                  "AshDieback",
                                  "SOD"),
                       labels = c("Xylella fastidiosa",
                                  "Liberbacter asiaticus",
                                  "Xanthomonas citri",
                                  "Hymenoscyphus fraxineus",
                                  "Phytophthora ramorum"),
                       discrete=TRUE) +
  annotate("text", x=(logGrowthPlotsNew$visPrev-0.005), y=(logGrowthPlotsNew$truePrev+0.012), label=logGrowthPlotsNew$label_r, size=6.5) +
  annotate("text", x=(logGrowthPlotsNew$visPrev-0.005), y=(logGrowthPlotsNew$truePrev-0.02), label=logGrowthPlotsNew$label_lag, size=6.5) +
  theme(legend.position=c(0.35,0.82),
        legend.title = element_blank(),
        legend.background=element_blank(),
        legend.text = element_markdown(face="italic"))

##### Effect of r and detection lag on sample size -----

maxR <- 0.050 # maximum r estimate for estimates
minR <- 0.001 # minimum r estimate for estimates
maxDetLag <- 365*2 # maximum detection lag estimate for estimates
minDetLag <- 0 # minimum detection lag estimate for estimates

rSeq <- seq(minR,maxR,minR)
detLagSeq <- seq(minDetLag,maxDetLag,1)

rDetLagAbsSampSing <- expand.grid(rSeq,detLagSeq)
names(rDetLagAbsSampSing) <- c("r","detLag")
rDetLagAbsSampSing$sampSize <- NA

detLagBreaks <- seq(minDetLag,maxDetLag,(365/12)*3)
detLagBreakLabs <- round(seq(minDetLag,maxDetLag,((365/12)*3)),0)
detLagMinorBreaks <- seq(minDetLag,maxDetLag,(365/12))

##### Single sample 

sampSizeAbsSampSing <- function(r,maxPrev,sens,detLag,perc){
  sampSize <- (log(1-perc)/sens)*(exp(r*detLag)*((maxPrev-1)/maxPrev)-1)
  return(sampSize)
}

# Estimates for X. fastidiosa
sampSizeAbsSampSing(rEst,maxPrev,testSensHost,asympPeriod,percentile)
sampSizeAbsSampSing(rMinXf,maxPrev,testSensHost,lambdaMinXf,percentile)
sampSizeAbsSampSing(rMaxXf,maxPrev,testSensHost,lambdaMaxXf,percentile)

# Estimates for all combinations
for(i in 1:nrow(rDetLagAbsSampSing)){
  rDetLagAbsSampSing$sampSize[i] <- sampSizeAbsSampSing(rDetLagAbsSampSing$r[i],maxPrev,testSensHost,rDetLagAbsSampSing$detLag[i],percentile)
}

plotBreaksLogScale <- seq(-1,10,1)

rScale <- c(0.001,0.0025,0.005,0.01,0.025)

rLogScale <- log10(rScale)

absSampSingContPlot <- ggplot(rDetLagAbsSampSing, aes(detLag, log10(r), z=sampSize)) +
  geom_segment(aes(x=lambdaMinSOD, xend=lambdaMaxSOD, y=log10(rSOD), yend=log10(rSOD)), lwd=2, colour=viridis(5)[5]) +
  geom_segment(aes(x=asympSOD, xend=asympSOD, y=log10(rMinSOD), yend=log10(rMaxSOD)), lwd=2, colour=viridis(5)[5]) +
  geom_point(aes(x=asympSOD,y=log10(rSOD)), size=4, colour=viridis(5)[5]) +
  geom_point(aes(x=lambdaMinSOD,y=log10(rSOD)), size=3, colour=viridis(5)[5]) +
  geom_point(aes(x=lambdaMaxSOD,y=log10(rSOD)), size=3, colour=viridis(5)[5]) +
  geom_point(aes(x=asympSOD,y=log10(rMinSOD)), size=3, colour=viridis(5)[5]) +
  geom_point(aes(x=asympSOD,y=log10(rMaxSOD)), size=3, colour=viridis(5)[5]) +
  geom_segment(aes(x=lambdaMinAshDieback, xend=lambdaMaxAshDieback, y=log10(rAshDieback), yend=log10(rAshDieback)), lwd=2, colour=viridis(5)[1]) +
  geom_segment(aes(x=asympAshDieback, xend=asympAshDieback, y=log10(rMinAshDieback), yend=log10(rMaxAshDieback)), lwd=2, colour=viridis(5)[1]) +
  geom_point(aes(x=asympAshDieback,y=log10(rAshDieback)), size=4, colour=viridis(5)[1]) +
  geom_point(aes(x=lambdaMinAshDieback,y=log10(rAshDieback)), size=3, colour=viridis(5)[1]) +
  geom_point(aes(x=lambdaMaxAshDieback,y=log10(rAshDieback)), size=3, colour=viridis(5)[1]) +
  geom_point(aes(x=asympAshDieback,y=log10(rMinAshDieback)), size=3, colour=viridis(5)[1]) +
  geom_point(aes(x=asympAshDieback,y=log10(rMaxAshDieback)), size=3, colour=viridis(5)[1]) +
  geom_segment(aes(x=lambdaMinCanker, xend=lambdaMaxCanker, y=log10(rCanker), yend=log10(rCanker)), lwd=2, colour=viridis(5)[2]) +
  geom_segment(aes(x=asympCanker, xend=asympCanker, y=log10(rMinCanker), yend=log10(rMaxCanker)), lwd=2, colour=viridis(5)[2]) +
  geom_point(aes(x=asympCanker,y=log10(rCanker)), size=4, colour=viridis(5)[2]) +
  geom_point(aes(x=lambdaMinCanker,y=log10(rCanker)), size=3, colour=viridis(5)[2]) +
  geom_point(aes(x=lambdaMaxCanker,y=log10(rCanker)), size=3, colour=viridis(5)[2]) +
  geom_point(aes(x=asympCanker,y=log10(rMinCanker)), size=3, colour=viridis(5)[2]) +
  geom_point(aes(x=asympCanker,y=log10(rMaxCanker)), size=3, colour=viridis(5)[2]) +
  geom_segment(aes(x=lambdaMinHLB, xend=lambdaMaxHLB, y=log10(rHLB), yend=log10(rHLB)), lwd=2, colour=viridis(5)[3]) +
  geom_segment(aes(x=asympHLB, xend=asympHLB, y=log10(rMinHLB), yend=log10(rMaxHLB)), lwd=2, colour=viridis(5)[3]) +
  geom_point(aes(x=asympHLB,y=log10(rHLB)), size=4, colour=viridis(5)[3]) +
  geom_point(aes(x=lambdaMinHLB,y=log10(rHLB)), size=3, colour=viridis(5)[3]) +
  geom_point(aes(x=lambdaMaxHLB,y=log10(rHLB)), size=3, colour=viridis(5)[3]) +
  geom_point(aes(x=asympHLB,y=log10(rMinHLB)), size=3, colour=viridis(5)[3]) +
  geom_point(aes(x=asympHLB,y=log10(rMaxHLB)), size=3, colour=viridis(5)[3]) +
  geom_segment(aes(x=lambdaMinXf, xend=lambdaMaxXf, y=log10(rEst), yend=log10(rEst)), lwd=2, colour=viridis(5)[4]) +
  geom_segment(aes(x=asympPeriod, xend=asympPeriod, y=log10(rMinXf), yend=log10(rMaxXf)), lwd=2, colour=viridis(5)[4]) +
  geom_point(aes(x=asympPeriod,y=log10(rEst)), size=4, colour=viridis(5)[4]) +
  geom_point(aes(x=lambdaMinXf,y=log10(rEst)), size=3, colour=viridis(5)[4]) +
  geom_point(aes(x=lambdaMaxXf,y=log10(rEst)), size=3, colour=viridis(5)[4]) +
  geom_point(aes(x=asympPeriod,y=log10(rMinXf)), size=3, colour=viridis(5)[4]) +
  geom_point(aes(x=asympPeriod,y=log10(rMaxXf)), size=3, colour=viridis(5)[4]) +
  geom_contour(aes(colour=..level..), colour="black", breaks=10^plotBreaksLogScale, lwd=1) +
  scale_y_continuous(limits = c(min(rLogScale),max(rLogScale)),
                     breaks = rLogScale,
                     labels = rScale) +
  labs(y = "Exponential growth rate") +
  scale_x_continuous(name ="Detection lag (days)",
                     breaks = detLagBreaks,
                     minor_breaks = detLagMinorBreaks,
                     labels = detLagBreakLabs) +
  theme_bw(base_size=40) 
absSampSingContPlot = direct.label(absSampSingContPlot, list("bottom.pieces", colour='black', cex=2))

##### Putting panels together: Figure 4
relPrevPlotsPanel <- relPrevPlots +
  labs(tag="A")
absSampSingContPlotPanel <- absSampSingContPlot +
  labs(tag="B")
fig4Plots <- relPrevPlotsPanel|absSampSingContPlotPanel
ggsave("plots/fig04.png",fig4Plots,width=30,height=10)
ggsave("plots/fig04.eps",fig4Plots,width=30,height=10)

##### Multiple samples (not shown in MS so code for figures hashed out)

sampSizeAbsSampMult <- function(r,maxPrev,sens,detLag,perc,sampInt){
  sampSize <- (log(1-perc)/sens)*(exp(r*detLag)*((maxPrev-1)/maxPrev)-1)*(1-exp(-r*sampInt))
  return(sampSize)
}

# rDetLagAbsSampMult <- expand.grid(rSeq,detLagSeq)
# names(rDetLagAbsSampMult) <- c("r","detLag")
# rDetLagAbsSampMult$sampSize <- NA
# 
# 
# sampSizeAbsSampMult(rEst,maxPrev,testSensHost,asympPeriod,percentile,sampInterval)
# sampSizeAbsSampMult(rMinXf,maxPrev,testSensHost,lambdaMinXf,percentile,sampInterval)
# sampSizeAbsSampMult(rMaxXf,maxPrev,testSensHost,lambdaMaxXf,percentile,sampInterval)
# 
# for(i in 1:nrow(rDetLagAbsSampMult)){
#   rDetLagAbsSampMult$sampSize[i] <- sampSizeAbsSampMult(rDetLagAbsSampMult$r[i],maxPrev,testSensHost,rDetLagAbsSampMult$detLag[i],percentile,sampInterval)
# }
# 
# absSampMultContPlot <- ggplot(rDetLagAbsSampMult, aes(detLag, log10(r), z=sampSize)) +
#   geom_segment(aes(x=lambdaMinSOD, xend=lambdaMaxSOD, y=log10(rSOD), yend=log10(rSOD)), lwd=2, colour=viridis(5)[5]) +
#   geom_segment(aes(x=asympSOD, xend=asympSOD, y=log10(rMinSOD), yend=log10(rMaxSOD)), lwd=2, colour=viridis(5)[5]) +
#   geom_point(aes(x=asympSOD,y=log10(rSOD)), size=4, colour=viridis(5)[5]) +
#   geom_point(aes(x=lambdaMinSOD,y=log10(rSOD)), size=3, colour=viridis(5)[5]) +
#   geom_point(aes(x=lambdaMaxSOD,y=log10(rSOD)), size=3, colour=viridis(5)[5]) +
#   geom_point(aes(x=asympSOD,y=log10(rMinSOD)), size=3, colour=viridis(5)[5]) +
#   geom_point(aes(x=asympSOD,y=log10(rMaxSOD)), size=3, colour=viridis(5)[5]) +
#   geom_segment(aes(x=lambdaMinAshDieback, xend=lambdaMaxAshDieback, y=log10(rAshDieback), yend=log10(rAshDieback)), lwd=2, colour=viridis(5)[1]) +
#   geom_segment(aes(x=asympAshDieback, xend=asympAshDieback, y=log10(rMinAshDieback), yend=log10(rMaxAshDieback)), lwd=2, colour=viridis(5)[1]) +
#   geom_point(aes(x=asympAshDieback,y=log10(rAshDieback)), size=4, colour=viridis(5)[1]) +
#   geom_point(aes(x=lambdaMinAshDieback,y=log10(rAshDieback)), size=3, colour=viridis(5)[1]) +
#   geom_point(aes(x=lambdaMaxAshDieback,y=log10(rAshDieback)), size=3, colour=viridis(5)[1]) +
#   geom_point(aes(x=asympAshDieback,y=log10(rMinAshDieback)), size=3, colour=viridis(5)[1]) +
#   geom_point(aes(x=asympAshDieback,y=log10(rMaxAshDieback)), size=3, colour=viridis(5)[1]) +
#   geom_segment(aes(x=lambdaMinCanker, xend=lambdaMaxCanker, y=log10(rCanker), yend=log10(rCanker)), lwd=2, colour=viridis(5)[2]) +
#   geom_segment(aes(x=asympCanker, xend=asympCanker, y=log10(rMinCanker), yend=log10(rMaxCanker)), lwd=2, colour=viridis(5)[2]) +
#   geom_point(aes(x=asympCanker,y=log10(rCanker)), size=4, colour=viridis(5)[2]) +
#   geom_point(aes(x=lambdaMinCanker,y=log10(rCanker)), size=3, colour=viridis(5)[2]) +
#   geom_point(aes(x=lambdaMaxCanker,y=log10(rCanker)), size=3, colour=viridis(5)[2]) +
#   geom_point(aes(x=asympCanker,y=log10(rMinCanker)), size=3, colour=viridis(5)[2]) +
#   geom_point(aes(x=asympCanker,y=log10(rMaxCanker)), size=3, colour=viridis(5)[2]) +
#   geom_segment(aes(x=lambdaMinHLB, xend=lambdaMaxHLB, y=log10(rHLB), yend=log10(rHLB)), lwd=2, colour=viridis(5)[3]) +
#   geom_segment(aes(x=asympHLB, xend=asympHLB, y=log10(rMinHLB), yend=log10(rMaxHLB)), lwd=2, colour=viridis(5)[3]) +
#   geom_point(aes(x=asympHLB,y=log10(rHLB)), size=4, colour=viridis(5)[3]) +
#   geom_point(aes(x=lambdaMinHLB,y=log10(rHLB)), size=3, colour=viridis(5)[3]) +
#   geom_point(aes(x=lambdaMaxHLB,y=log10(rHLB)), size=3, colour=viridis(5)[3]) +
#   geom_point(aes(x=asympHLB,y=log10(rMinHLB)), size=3, colour=viridis(5)[3]) +
#   geom_point(aes(x=asympHLB,y=log10(rMaxHLB)), size=3, colour=viridis(5)[3]) +
#   geom_segment(aes(x=lambdaMinXf, xend=lambdaMaxXf, y=log10(rEst), yend=log10(rEst)), lwd=2, colour=viridis(5)[4]) +
#   geom_segment(aes(x=asympPeriod, xend=asympPeriod, y=log10(rMinXf), yend=log10(rMaxXf)), lwd=2, colour=viridis(5)[4]) +
#   geom_point(aes(x=asympPeriod,y=log10(rEst)), size=4, colour=viridis(5)[4]) +
#   geom_point(aes(x=lambdaMinXf,y=log10(rEst)), size=3, colour=viridis(5)[4]) +
#   geom_point(aes(x=lambdaMaxXf,y=log10(rEst)), size=3, colour=viridis(5)[4]) +
#   geom_point(aes(x=asympPeriod,y=log10(rMinXf)), size=3, colour=viridis(5)[4]) +
#   geom_point(aes(x=asympPeriod,y=log10(rMaxXf)), size=3, colour=viridis(5)[4]) +
#   geom_contour(aes(colour=..level..), colour="black", breaks=10^plotBreaksLogScale, lwd=1) +
#   scale_y_continuous(limits = c(min(rLogScale),max(rLogScale)),
#                      breaks = rLogScale,
#                      labels = rScale) +
#   labs(y = "Exponential growth rate") +
#   scale_x_continuous(name ="Detection lag (days)",
#                      breaks = detLagBreaks,
#                      minor_breaks = detLagMinorBreaks,
#                      labels = detLagBreakLabs) +
#   theme_bw(base_size=40) 
# absSampMultContPlot = direct.label(absSampMultContPlot, list("bottom.pieces", colour='black', cex=2))

##### Effect of detection lag and sensitivity on sample size -----

detLagSensDF <- expand.grid(detLag=detLagSeq,
                                sens=seq(0.1,1,0.1),
                                absSampSing=NA,
                                absSampMult=NA)

detLagSensDF$absSampSing <- sampSizeAbsSampSing(rEst,maxPrev,detLagSensDF$sens,detLagSensDF$detLag,percentile)
detLagSensDF$absSampMult <- sampSizeAbsSampMult(rEst,maxPrev,detLagSensDF$sens,detLagSensDF$detLag,percentile,sampInterval)

detLagSensDFLong <- detLagSensDF %>%
  gather(estType, sampSize, absSampSing:absSampMult) %>%
  mutate(numSamps =
           ifelse(estType == "absSampSing", "sing",
                  ifelse(estType == "absSampMult", "mult", NA)))

maxSampSize <- detLagSensDF$absSampSing[which(detLagSensDF$sens==1 & detLagSensDF$detLag==365)]
visDetSampSize <- detLagSensDF$absSampSing[which(detLagSensDF$sens==testSensHost & detLagSensDF$detLag==asympPeriod)]

perfSensCol <- brewer.pal(10,"Spectral")[10]

detLagSampsize <- ggplot(filter(detLagSensDFLong, numSamps=="sing" & detLag<=365), aes(x=detLag, y=sampSize, colour=as.factor(sens))) +
  geom_line(lwd=2) +
  geom_vline(xintercept=asympPeriod, lty=2, lwd=2) +
  geom_hline(yintercept=visDetSampSize, lty=2, lwd=2) +
  scale_x_continuous(name ="Detection lag (days)",
                     breaks = detLagBreaks,
                     minor_breaks = detLagMinorBreaks,
                     labels = detLagBreakLabs
                     ) +
  scale_y_continuous(name ="Sample size",
                     limits = c(0,visDetSampSize*2)) +
  scale_colour_viridis(name = "Sensitivity",
                      breaks = c(1,0.7,0.4,0.1),
                      discrete=TRUE) +
  theme_bw(base_size=40) +
  theme(legend.position=c(0.15,0.75),
        legend.background=element_blank() ) 


##### Costs -----
visualCost <- 80 # cost of transport and wages for single inspector
numInsp <- 2 # number of inspectors in a surveillance team
treesPerDay <- (80+70)/2 # number of trees visited/inspected per team per day (mean of 70-80 range)
hostVisitCostVis <- (visualCost*numInsp)/treesPerDay  # cost of inspecting a single tree 
hostSampCostVis <- 5.48 # based on 2017 surveillance data
hostElisaCost <- (15+10)/2 # mean cost of using ELISA per tree (ignoring transportation costs)
hostTestCost <- hostVisitCostVis+hostElisaCost # cost of visiting and testing a tree

costRatFunc <- function(r,percentile,truePrev,sens1,detLag1,sens2,detLag2){
  test1 <- (-log(1-percentile)/sens1)*(1-(exp(r*detLag1))*(truePrev-1/truePrev))
  test2 <- (-log(1-percentile)/sens2)*(1-(exp(r*detLag2))*(truePrev-1/truePrev))
  costRatio <- test2/test1
  return(costRatio)
}

sensPoints <- seq(0.1,1,0.1)
detLagPoints <- seq(0,365,1)

sensDetLagCost <- expand.grid(sens=sensPoints,detLag=detLagPoints)
sensDetLagCost$costRatio <- NA

# Looking at the frontier (i.e. equivalence points)
for(i in 1:nrow(sensDetLagCost)){
  sensDetLagCost$costRatio[i] <- costRatFunc(r=rEst,
                                             percentile=percentile,
                                             truePrev=maxPrev, # note that this is needed for logistic estimation
                                             sens1=sensDetLagCost$sens[i],
                                             detLag1=sensDetLagCost$detLag[i],
                                             sens2=testSensHost,
                                             detLag2=asympPeriod)
}

maxCostRatio <- max(sensDetLagCost$costRatio)
minCostRatio <- min(sensDetLagCost$costRatio)

costRatBreaks <- seq(floor(log2(minCostRatio)),ceiling(log2(maxCostRatio)))
costRatBreakLabs <- costRatBreaks
costRatBreakLabs[which(costRatBreaks<0)] <- paste("1:",(1/2^(costRatBreaks[which(costRatBreaks<0)])),sep="")
costRatBreakLabs[which(costRatBreaks==0)] <- paste("1:1")
costRatBreakLabs[which(costRatBreaks>0)] <- paste((2^(costRatBreaks[which(costRatBreaks>0)])),":1",sep="")

diagTestSelection <- ggplot(sensDetLagCost, aes(x=detLag, y=log2(costRatio), colour=as.factor(sens))) +
  geom_line(lwd=2) +
  geom_hline(aes(yintercept=log2(hostTestCost/hostSampCostVis)),lwd=2,lty=3) +
  geom_vline(aes(xintercept=asympPeriod),lwd=2, lty=2) +
  geom_hline(aes(yintercept=log2(1)),lwd=2) +
  scale_x_continuous(name ="Detection lag (days)",
                     breaks = detLagBreaks,
                     minor_breaks = detLagMinorBreaks,
                     labels = detLagBreakLabs) +
  scale_y_continuous(name ="Test cost : visual inspection cost",
                     breaks = costRatBreaks,
                     labels = costRatBreakLabs) +
  scale_colour_viridis(name = "Sensitivity",
                      #breaks = c(0.1,0.4,0.7,1),
                      breaks = c(1,0.7,0.4,0.1),
                      discrete = TRUE) +
  theme_bw(base_size=40) +
  theme(legend.position=c(0.15,0.2),
        legend.background=element_blank() ) 


##### Putting panels together: Figure 5
detLagSampsizePanel <- detLagSampsize +
  labs(tag="A")
diagTestSelectionPanel <- diagTestSelection +
  labs(tag="B")
fig5Plots <- detLagSampsizePanel/diagTestSelectionPanel
ggsave("plots/fig05.png",fig5Plots,width=15,height=20)
ggsave("plots/fig05.eps",fig5Plots,width=15,height=20)


##### Fitting model to vector data -----

##### Vector density

vectDens <- data.frame(
  day = c(30,60,90,120,150,180,210,240,270,300,330,360),
  bmVect = c(0.026936,0,3.37E-03,0.16835,0.215488,0.37037,0.521886,0.680135,1.0,0.171717,0.03367,0.023569),
  cVect = c(NA,NA,NA,NA,0.513514,0.486486,1.0,0.324324,0.27027,0.040541,0,0)
)

vectDensLong <- gather(vectDens,"datSource","dens",-day)

vectDens$meanVect <- rowMeans(vectDens[,-1])

vectRelDensFunc <- function(C,g0,a,tEm,t){
  vectDens <- C*exp(g0*(t-tEm)-(a/2)*(t-tEm)^2)
  return(vectDens)
}

C <- 0.007265
g0 <- 0.064913 # rate of adult vector emergence
a <- 0.0004574 # rate of decline in numbers of adults over time
tEm <- 80 # time of first vector emergence

vectDens$pred <- vectRelDensFunc(C,g0,a,tEm,vectDens$day)

vectDensPreds <- data.frame(day=seq(1,365),
                            pred=NA)
vectDensPreds$pred <- vectRelDensFunc(C,g0,a,tEm,vectDensPreds$day)


vectDensDat <- ggplot(data=vectDensLong, aes(x=day, y=dens, colour=datSource)) +
  geom_point(size=4) +
  geom_point(data=vectDens, aes(x=day, y=meanVect),colour="black", size=5) +
  geom_line(data=vectDensPreds, aes(x=day, y=pred),colour="black",lwd=2) +
  labs(y="Relative density of adult vectors") +
  scale_x_continuous(name ="Day of the year",
                     breaks = detLagBreaks,
                     minor_breaks = detLagMinorBreaks,
                     labels = detLagBreakLabs) +
  scale_colour_viridis(name="Data source",
                       breaks = c("bmVect","cVect"),
                       labels = c("Ben-Moussa","Cornara"),
                       begin = 0.5,
                       end = 1,
                       discrete = TRUE) +
  theme_bw(base_size=30) +
  theme(legend.position=c(0.15,0.8))

##### Vector prevalence

vectPrev <- data.frame(
  day = c(30,60,90,120,150,180,210,240,270,300,330,360),
  bmVect = c(NA,NA,0,0,0,0.31,0.19,0.2,0.14,0.31,0.1,0),
  c1Vect = c(NA,NA,NA,NA,0.27,0.55,0.51,1.0,0.8,0.65,NA,NA),
  c2Vect = c(NA,NA,NA,NA,0.178,0.476,0.414,0.569,0.492,0.4579,NA,NA)
)
#write_csv(vectPrev, file="plots/vectPrev.csv")

vectPrevLong <- gather(vectPrev,"datSource","prev",-day)

vectPrev$meanVect <- rowMeans(vectPrev[,-1])


vectPrevFunc <- function(betaI,g0,tin,t){
  (betaI/(betaI+g0))*(1-exp(-(betaI+g0)*(t-tin)))
}

betaI <- 0.060887
t0 <- 150 # time of first vector infection
tx <- 300 # last day for which reasonable data available

# Adding predictions to observed dates
vectPrev$pred <- vectPrevFunc(betaI,g0,t0,vectPrev$day)
vectPrev$pred[which(vectPrev$day<t0)] <- 0
vectPrev$pred[which(vectPrev$day>tx)] <- 0

# Predicting prevalence for each day of the year
# (Assuming that prevalence maintained until end of year for ease of visualisation)
vectPrevPreds <- data.frame(day=seq(1,365),
                            pred=NA)
vectPrevPreds$pred <- vectPrevFunc(betaI,g0,t0,vectPrevPreds$day)
vectPrevPreds$pred[which(vectPrevPreds$day<t0)] <- 0

vectPrevDat <- ggplot(data=vectPrevLong, aes(x=day, y=prev, colour=datSource)) +
  geom_point(size=4) +
  geom_point(data=vectPrev, aes(x=day, y=meanVect),colour="black", size=5) +
  geom_line(data=vectPrevPreds, aes(x=day, y=pred),colour="black",lwd=2) +
  labs(y="Esimtated prevalence in vectors") +
  scale_x_continuous(name ="Day of the year",
                     breaks = detLagBreaks,
                     minor_breaks = detLagMinorBreaks,
                     labels = detLagBreakLabs) +
  scale_colour_viridis(name="Data source",
                       breaks = c("bmVect","c1Vect","c2Vect"),
                       labels = c("Ben-Moussa","Cornara JPS","Cornara JAE"),
                       begin = 0.25,
                       end = 1,
                       discrete = TRUE) +
  theme_bw(base_size=30) +
  theme(legend.position=c(0.15,0.8))

##### Putting panels together: Figure 2
vectDensDatPanel <- vectDensDat +
  labs(tag="A")
vectPrevDatPanel <- vectPrevDat +
  labs(tag="B")
fig2Plots <- vectDensDatPanel/vectPrevDatPanel
ggsave("plots/fig02.png",fig2Plots,width=15,height=20)
ggsave("plots/fig02.eps",fig2Plots,width=15,height=20)

##### Running host-vector model -----

P0 <- 20 # max overall density of vectors
hvBeta <- 21.442828 # acquisiton rate
alpha <- 8.579169e-06 # inoculation rate
hostDens <- 1/81 # host density
alphaA <- 0.11643
K <- 0.725 # max. rel density from vector model

totYears <- 5
initDensInfHost <-  hostDens*0.001

hostPrevDifferenceEq <- function(I,hostDens,alphaA,beta,P0,K,g0){
  newI <- I + (hostDens-I)*(1-exp(-alphaA*((beta*I*(P0/K))/(beta*I+g0))))
  return(newI)
}

hostPrev <- data.frame(year = seq(1,totYears),
                       hostInfDens = NA,
                       hostPrev = NA)
hostPrev$hostInfDens[1] <- initDensInfHost

for(i in 2:totYears){
  hostPrev$hostInfDens[i] <- hostPrevDifferenceEq(hostPrev$hostInfDens[(i-1)],hostDens,alphaA,hvBeta,P0,K,g0)
}
hostPrev$hostPrev <- hostPrev$hostInfDens/hostDens

vectHostPrevFunc <- function(I,beta,g0,t0,t){
  vectPrev <- (beta*I/(beta*I+g0))*(1-exp(-(beta*I+g0)*(t-t0)))
  return(vectPrev)
}

vectInfDensFunc <- function(P0,g0,a,I,beta,t0,t){
  vectInfDens <- (beta*I*P0/(beta*I+g0))*(1-exp(-(beta*I+g0)*(t-t0)))*exp(g0*(t-t0)-(a/2)*(t-t0)^2)
  return(vectInfDens)
}


vectPrevDF <- data.frame(seqDate =seq(1,365*totYears),
                       year = rep(1:5, each=365),
                       day = rep(seq(0:364),totYears),
                       vectDens = NA,
                       vectInfDens = NA,
                       vectPrev = NA)

for(i in 1:(totYears*365)){
  infHostDens <- hostPrev$hostInfDens[which(hostPrev$year==vectPrevDF$year[i])]
  vectPrevDF$vectDens[i] <- vectRelDensFunc(((P0/K)*C),g0,a,tEm,vectPrevDF$day[i])
  vectPrevDF$vectInfDens[i] <- vectInfDensFunc(((P0/K)*C),g0,a,infHostDens,hvBeta,tEm,vectPrevDF$day[i])
  vectPrevDF$vectPrev[i] <- vectHostPrevFunc(infHostDens,hvBeta,g0,t0,vectPrevDF$day[i])
  if(vectPrevDF$day[i]<t0){
    vectPrevDF$vectPrev[i] <- 0
    if(vectPrevDF$day[i]<tEm){
      vectPrevDF$vectInfDens[i] <- 0
    }
  }
}

##### Putting all together
hostvectPrev <- data.frame(seqDate =rep(seq(1,365*totYears),2),
                           year = rep(rep(1:5, each=365),2),
                           day = rep(rep(seq(0:364),totYears),2),
                           group = c(rep("host",365*totYears),rep("vect",365*totYears)),
                           dens = NA,
                           infDens = NA,
                           prev = NA)
hostvectPrev$dens[which(hostvectPrev$group=="host")] <- hostDens
hostvectPrev$infDens[which(hostvectPrev$group=="host")] <- rep(hostPrev$hostInfDens,each=365)
hostvectPrev$prev[which(hostvectPrev$group=="host")] <- rep(hostPrev$hostPrev,each=365)
hostvectPrev$dens[which(hostvectPrev$group=="vect")] <- vectPrevDF$vectDens
hostvectPrev$infDens[which(hostvectPrev$group=="vect")] <- vectPrevDF$vectInfDens
hostvectPrev$prev[which(hostvectPrev$group=="vect")] <- vectPrevDF$vectPrev
hostvectPrev$prev[which(hostvectPrev$day==1)]<-NA

monthMarkers <- seq(1,totYears*12)
monthNames <- rep(month.abb,totYears)
monthPoints <- seq(1,totYears*365,365/12)
monthLetters <- rep(c("J","F","M","A","M","J","J","A","S","O","N","D"),totYears)
yearMarkers <- seq(0,totYears*365,365)
monthPoints2 <- seq(1,totYears*365,(365/12)*6)
monthLetters2 <- rep(c("Jan","Jul"),totYears)
yearsSubset <- 2 # number of years for subset graph


vectPlotColours <- c("total vectors" = viridis(2)[1],
                     "infected vectors" = viridis(2)[2])

vectDensInfModel <- ggplot(data=filter(hostvectPrev,group=="vect"),aes(x=seqDate)) +
  geom_line(aes(y=dens, col="total vectors"),lwd=2) +
  geom_line(aes(y=infDens, col="infected vectors"),lwd=2) +
  labs(y = "Vector density (per square metre)",
       col="") +
  scale_x_continuous(name ="Month",
                     breaks = monthPoints2,
                     labels = monthLetters2) +
  geom_vline(xintercept=yearMarkers,lty=2,col="grey") +
  scale_colour_manual(values = vectPlotColours) +
  theme_bw(base_size = 40) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.position=c(0.5,1), legend.justification=c(0.5,0), legend.direction='horizontal',legend.background = element_rect(fill="transparent")) 

hostvectPrevModelFull <- ggplot(data=hostvectPrev,aes(x=seqDate,y=prev,col=group)) +
  geom_line(lwd=2) +
  labs(y = "Prevalence") + ylim(c(0,1)) +
  scale_x_continuous(name ="Month",
                     breaks = monthPoints2,
                     labels = monthLetters2) +
  scale_colour_viridis(name = "Group", labels = c("Hosts","Vectors"), discrete = TRUE, begin = 0.75, end = 0.25) +
  theme_bw(base_size = 40) +
  theme(legend.position = "none") +
  geom_vline(xintercept=yearMarkers,lty=2,col="grey")

hostvectPrevModelSubset <- ggplot(data=filter(hostvectPrev,seqDate<=(365*yearsSubset)), aes(x=seqDate,y=prev,col=group)) +
  geom_line(lwd=2) +
  labs(y = "Prevalence") +
  scale_x_continuous(name ="Month",
                     breaks = monthPoints[which(monthPoints<=365*yearsSubset)],
                     labels = monthLetters[which(monthPoints<=365*yearsSubset)],
                     lim = c(0,365*yearsSubset)) +
  scale_colour_viridis(name = "Group", labels = c("Hosts","Vectors"), discrete = TRUE, begin = 0.75, end = 0.25) +
  theme_bw(base_size = 40) +
  theme(legend.justification=c(0,1), legend.position=c(0.01,0.99), legend.text = element_text(size=28),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(),
        axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank()) +
  geom_vline(xintercept=yearMarkers,lty=2,col="grey",lwd=2) +
  geom_vline(xintercept=monthPoints,lty=3,col="grey",lwd=1)

hostvectPrevModel <- hostvectPrevModelFull +
  annotation_custom(ggplotGrob(hostvectPrevModelSubset), xmin = -100, xmax = (365*2), 
                  ymin = 0.125, ymax = 1.05)


##### Putting panels together: Figure 3
vectDensInfModelPanel <- vectDensInfModel +
  labs(tag="A")
hostvectPrevModelPanel <- hostvectPrevModel +
  labs(tag="B")
fig3Plots <- vectDensInfModelPanel/hostvectPrevModelPanel
ggsave("plots/fig03.png",fig3Plots,width=15,height=20)
ggsave("plots/fig03.eps",fig3Plots,width=15,height=20)

##### Host-vector sampling -----

# Already have estimates of host test parameters (see above)
testSensVect <- 0.82
testSpecVect <- 1
numSampRounds <- 1

peakSampRat <- hostDens*hvBeta/g0 # vect:host prev ratio if sample vectors at peak time.
selYear <- 1
maxHostPrev <- hostvectPrev %>%
  filter(group=="host" & year==selYear) %>%
  slice(which.max(prev)) %>%
  select(prev)
maxVectPrev <- hostvectPrev %>%
  filter(group=="vect" & year==selYear) %>%
  slice(which.max(prev)) %>%
  select(prev)
maxVectPrev/maxHostPrev

zProd <- exp(-rEst*(numSampRounds-1)*sampInterval) # use exponential growth assumption to estimate prevalences at all previous sampling rounds

# Function below estimates the B parameter
parameterBFunc <- function(sampsizeHost,testSensHost,sampsizeVect,testSensVect,testSpecVect,peakSampRat,zProd){
  parameterB <- ((1-(1-testSensHost))*sampsizeHost + (1-((1-testSensVect)/testSpecVect))*sampsizeVect*peakSampRat)*zProd
  return(parameterB)
}

##### Sample size
sampSizeSeq <- seq(1,50000,1)
maxPrevAxis <- 0.05

# Apparent host prevalence 
prevNoDetHostSamp <- -log(1-percentile)/parameterBFunc(sampSizeSeq,testSensHost,0,testSensVect,testSpecVect,peakSampRat,zProd)
prevNoDetVectSamp <- -log(1-percentile)/parameterBFunc(0,testSensHost,sampSizeSeq,testSensVect,testSpecVect,peakSampRat,zProd)

# Adjusting for logistic growth when estimating the associated true host prevalence
prevNoDetIncLagHostSamp <- prevNoDetHostSamp*exp(rEst*asympPeriod)/(1+prevNoDetHostSamp*(exp(rEst*asympPeriod)-1))
prevNoDetIncLagVectSamp <- prevNoDetVectSamp*exp(rEst*asympPeriod)/(1+prevNoDetVectSamp*(exp(rEst*asympPeriod)-1))

prevNoDetSampSize <- data.frame(sampSize = rep(sampSizeSeq,2),
                                group = c(rep("host",length(sampSizeSeq)),rep("vect",length(sampSizeSeq))),
                                prev = c(prevNoDetIncLagHostSamp,prevNoDetIncLagVectSamp))

maxSampSizeHV <- max(10000,prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="host" & prevNoDetSampSize$prev<maxPrev)][1],prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="vect" & prevNoDetSampSize$prev<maxPrev)][1])

hvSampSize2 <- ggplot(data=filter(prevNoDetSampSize,sampSize<(maxSampSizeHV*1.1)),aes(x=prev, y=sampSize, colour=group)) +
  geom_line(lwd=2) +
  geom_vline(xintercept = maxPrev, lwd=2,lty=2) +
  geom_hline(yintercept = prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="host" & prevNoDetSampSize$prev<maxPrev)][1], lwd=2,lty=2) +
  geom_hline(yintercept = prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="vect" & prevNoDetSampSize$prev<maxPrev)][1], lwd=2,lty=2) +
  labs(x = "Maximum true host prevalence", y = "Number sampled") + xlim(c(0,maxPrevAxis)) +
  scale_colour_viridis(name = "Group", labels = c("Host visual assessment","Vector PCR"), discrete = TRUE) +
  theme_bw(base_size = 40) +
  theme(legend.justification=c(1,1), legend.position=c(0.99,0.99), legend.text = element_text(size=40))


prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="host" & prevNoDetSampSize$prev<maxPrev)][1]
prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="vect" & prevNoDetSampSize$prev<maxPrev)][1]

##### Sample costs

# Assuming vector pooling
vectorCost <- 80 # cost of collecting vectors
vectorsPerDay <- (60+150)/2 # vectors collected per day for testing
vectCollectionCost <- vectorCost/vectorsPerDay  # cost of collecting a single vector
vectPcrPool <- 5 # number of vectors pooled for PCR
vectPcrCostSing <- ((20+35)/2) # mean cost of using PCR 
vectPcrCostPool <- vectPcrCostSing/vectPcrPool # mean cost of using PCR per vector (can be pooled up to 5)
vectPcrSens <- (1-0.18)
vectSampCostTotPcrSing <- vectCollectionCost+vectPcrCostSing # total vector sampling cost if PCR testing
vectSampCostTotPcrPool <- vectCollectionCost+vectPcrCostPool # total vector sampling cost if PCR testing

testSensHostELISA <- 0.1 # 
hostSampCostTot <- 5.48 # based on 2017 surveillance data 
hostELISADetLag <- 365/4 

maxCost <- 100000
costSeq <- seq(1,maxCost,1)

hostSampSizeELISA <- costSeq/hostElisaCost # assuming that all samples are sent to lab
hostSampSizeVis <- costSeq/hostSampCostTot # assuming that all positive samples are sent to lab
vectSampSizePcrSing <- costSeq/vectSampCostTotPcrSing 
vectSampSizePcrPool <- costSeq/vectSampCostTotPcrPool

prevNoDetHostELISASamp <- -log(1-percentile)/parameterBFunc(hostSampSizeELISA,testSensHostELISA,0,testSensVect,testSpecVect,peakSampRat,zProd)
prevNoDetHostVisSamp <- -log(1-percentile)/parameterBFunc(hostSampSizeVis,testSensHost,0,testSensVect,testSpecVect,peakSampRat,zProd)
prevNoDetVectPcrSampSing <- -log(1-percentile)/parameterBFunc(0,testSensHost,vectSampSizePcrSing,vectPcrSens,testSpecVect,peakSampRat,zProd)
prevNoDetVectPcrSampPool <- -log(1-percentile)/parameterBFunc(0,testSensHost,vectSampSizePcrPool,vectPcrSens,testSpecVect,peakSampRat,zProd)

prevNoDetIncLagELISAHostSamp <- prevNoDetHostELISASamp*exp(rEst*hostELISADetLag)/(1+prevNoDetHostELISASamp*(exp(rEst*hostELISADetLag)-1))
prevNoDetIncLagVisHostSamp <- prevNoDetHostVisSamp*exp(rEst*asympPeriod)/(1+prevNoDetHostVisSamp*(exp(rEst*asympPeriod)-1))
prevNoDetIncLagVectPcrSampSing <- prevNoDetVectPcrSampSing*exp(rEst*asympPeriod)/(1+prevNoDetVectPcrSampSing*(exp(rEst*asympPeriod)-1))
prevNoDetIncLagVectPcrSampPool <- prevNoDetVectPcrSampPool*exp(rEst*asympPeriod)/(1+prevNoDetVectPcrSampPool*(exp(rEst*asympPeriod)-1))

prevNoDetSampCost <- data.frame(sampCost = rep(costSeq,4),
                                group = c(rep("hostVis",length(costSeq)),
                                          rep("hostELISA",length(costSeq)),
                                          rep("vectPcrSing",length(costSeq)),
                                          rep("vectPcrPool",length(costSeq))),
                                prev = c(prevNoDetIncLagVisHostSamp,
                                         prevNoDetIncLagELISAHostSamp,
                                         prevNoDetIncLagVectPcrSampSing,
                                         prevNoDetIncLagVectPcrSampPool))

hvSampCostAll <- ggplot(data=prevNoDetSampCost,aes(x=sampCost, y=prev, colour=group)) +
  geom_line(lwd=2) +
  labs(y = "Maximum prevalence", x = "Sampling costs (Euro)") +
  ylim(c(0,0.4)) +
  xlim(c(0,20000)) +
  scale_colour_viridis(name = "Group",
                        breaks = c("hostVis","hostELISA","vectPcrSing","vectPcrPool"),
                        labels = c("Hosts (Visual)","Hosts (ELISA)","Vectors (single PCR)","Vectors (pooled PCR)"),
                       discrete = TRUE) +
  theme_bw(base_size = 28) +
  theme(legend.justification=c(1,1), legend.position=c(0.99,0.99), legend.text = element_text(size=28))


hvSampCost2 <- ggplot(data=filter(prevNoDetSampCost,group=="hostVis" | group=="vectPcrSing" |group=="vectPcrPool") ,aes(x=prev, y=sampCost, colour=group)) +
  geom_line(lwd=2) +
  geom_vline(xintercept = maxPrev, lwd=2,lty=2) +
  geom_hline(yintercept = prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="hostVis" & prevNoDetSampCost$prev<maxPrev)][1], lwd=2,lty=2) +
  geom_hline(yintercept = prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="vectPcrSing" & prevNoDetSampCost$prev<maxPrev)][1], lwd=2,lty=2) +
  geom_hline(yintercept = prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="vectPcrPool" & prevNoDetSampCost$prev<maxPrev)][1], lwd=2,lty=2) +
  labs(x = "Maximum true host prevalence", y = "Sampling costs (Euro)") +
  xlim(c(0,maxPrevAxis)) +
  ylim(c(0,maxCost)) +
  scale_colour_viridis(name = "Detection method",
                       breaks = c("hostVis","vectPcrSing","vectPcrPool"),
                       labels = c("Host visual assessment","Single vector PCR","Pooled vector PCR"), 
                       discrete = TRUE) +
  theme_bw(base_size = 40) +
  theme(legend.justification=c(1,1), legend.position=c(0.99,0.99), legend.text = element_text(size=28))


prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="hostVis" & prevNoDetSampCost$prev<maxPrev)][1]
prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="vectPcrSing" & prevNoDetSampCost$prev<maxPrev)][1]
prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="vectPcrPool" & prevNoDetSampCost$prev<maxPrev)][1]

##### Putting panels together: Figure 6
hvSampSizePanel <- hvSampSize2 +
  labs(tag="A")
hvSampCostPanel <- hvSampCost2 +
  labs(tag="B")
fig6Plots <- hvSampSizePanel/hvSampCostPanel
ggsave("plots/fig06.png",fig6Plots,width=15,height=20)
ggsave("plots/fig06.eps",fig6Plots,width=15,height=20)