###### This code allows manipulation of the vector prevalence estimates used for predicting early stage host and vector prevalences and generates outputs similar to those in the main paper

library(tidyverse)
library(ggthemes) # for plotting
library(scales) # for plotting
library(viridis) # for plotting
library(RColorBrewer) # for plotting
library(directlabels) # for plotting
library(patchwork) #  for plotting


##### Define parameter values here -----

percentile <- 0.90 # percentile as a proportion
maxPrev <- 0.01 # maximum acceptable prevalence if no detections

rEst <- 0.0122 # mean r for system (per day)

numSampRounds <- 1 # number of sampling rounds
sampInterval <- 365/4 # interval between sampling rounds (days) if more than one round

testSensHost <- 1 # sensitivity of detection method in hosts
asympPeriod <- 313 # duration of asymptomatic period in hosts
testSensVect <- 0.82 # test sensitivity in vectors
testSpecVect <- 1 # test specificity in vectors
# Note: assuming detection method in hosts has perfect specificity, and that there is no detection lag in vectors

# Specify vector fits below
modelFit <- 1 # use original fits (1), fit to current data (2), or specify own prevalence plateau (3)
# Note that due to different fitting algorithms and the limited available data, the precise fit to the current prevalence data differs from that described in the paper. However, this does not affect the final model conclusions.

plateauPrev <- 0.2 # plateau prevalence (only used if modelFit==3)
saveOutput <- 1 # save output plots (1) or not (0)

##### Load in available 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])

##### 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)
)
vectPrevLong <- gather(vectPrev,"datSource","prev",-day)
vectPrev$meanVect <- rowMeans(vectPrev[,-1])

##### Specifying timings and subsetting data
tEm <- 80 # time of first vector emergence
t0 <- 150 # time of first vector infection
tx <- 300 # last day for which reasonable prevalence data available

vectPrevAdj <- vectPrev %>%
  filter(day>=t0) %>%
  mutate(day=day-t0)

vectDensAdj <- vectDens %>%
  filter(day>=tEm) %>%
  mutate(day=day-tEm)

##### Estimating/specifying parameters -----

if(modelFit==2){
  # This code fits nonlinear regression models to the data to estimate the required parameters
  prevFit <- nls(meanVect ~ A*(1-exp(-(B*day))), data=vectPrevAdj, start=list(A=0.5, B=0.1), trace=T)
  betaI_betaIg0 <- as.numeric(coefficients(prevFit)[1])
  betaIg0 <- as.numeric(coefficients(prevFit)[2]) 
  betaI <- betaI_betaIg0*betaIg0
  g0 <- betaIg0-betaI # rate of adult vector emergence
  
  densFit <- nls(meanVect ~ C*exp((g0*day)-((a/2)*(day^2))), data=vectDensAdj, start=list(C=0.07, a=0.0005), na.action=na.omit)
  C <- as.numeric(coefficients(densFit)[1])
  a <- as.numeric(coefficients(densFit)[2]) # rate of decline in numbers of adults over time
  
  plotName <- "fitPar"
}

if(modelFit==1 | modelFit==3){
  # This code is based upon the original parameter estimates used in the paper, which can be adjusted if desired
  g0 <- 0.064913
  if(modelFit==1){
    betaI <- 0.060887
    C <- 0.007265
    a <- 0.0004574
    plotName <- "origPar"
  }
  
  if(modelFit==3){
    betaI_betaIg0_new <- plateauPrev
    betaIg0_new <- g0/(1-betaI_betaIg0_new)
    betaI_new <- betaI_betaIg0_new*betaIg0_new
    g0_new <- betaIg0_new-betaI_new
    
    # Refitting density curve
    densFit <- nls(meanVect ~ C*exp((g0_new*day)-((a/2)*(day^2))), data=vectDensAdj, start=list(C=0.07, a=0.0005), na.action=na.omit)
    C_new <- as.numeric(coefficients(densFit)[1])
    a_new <- as.numeric(coefficients(densFit)[2])
    
    betaI_betaIg0 <- betaI_betaIg0_new
    betaIg0 <- betaIg0_new
    betaI <- betaI_new
    g0 <- g0_new
    C <- C_new
    a <- a_new
    plotName <- paste0("prev",round(plateauPrev*100))
  }
}

##### Visualising the curve fits with the selected parameters -----

maxDetLag <- 365*2 # maximum detection lag estimate for estimates
minDetLag <- 0 # minimum detection lag estimate for estimates
detLagBreaks <- seq(minDetLag,maxDetLag,(365/12)*3)
detLagBreakLabs <- round(seq(minDetLag,maxDetLag,((365/12)*3)),0)
detLagMinorBreaks <- seq(minDetLag,maxDetLag,(365/12))


vectRelDensFunc <- function(C,g0,a,tEm,t){
  vectDens <- C*exp(g0*(t-tEm)-(a/2)*(t-tEm)^2)
  return(vectDens)
}

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))


vectPrevFunc <- function(betaI,g0,tin,t){
  (betaI/(betaI+g0))*(1-exp(-(betaI+g0)*(t-tin)))
}

# 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
if(saveOutput==1){
  ggsave(paste0("plots/01_curveFits_",plotName,".png"),fig2Plots,width=15,height=20)
  ggsave(paste0("plots/01_curveFits_",plotName,".eps"),fig2Plots,width=15,height=20)
}

##### Running host-vector model -----

Pmax <- 20 # maximum overall density of vectors
K <- max(vectDens$pred) # max. rel density from vector model
P0 <- Pmax/K
propInfHosts <- 0.23 # estimated proportion of infected hosts in vector study area
hostDens <- 1/81 # host density

betaD <- betaI/propInfHosts
beta <- betaD/hostDens

A1 <- integrate(function(x){(1-exp(-g0*(x-t0)))*vectRelDensFunc(C=1,g0=g0,a=a,tEm=tEm,t=x)}, lower = t0, upper = 365)$value

dA_dI <- P0*(beta/g0)*A1
lambdaEst <- exp(rEst*(365-t0))
alpha <- (lambdaEst-1)/(hostDens*dA_dI)

A2 <- mean(c(integrate(function(x){(1-exp(-((beta*0)+g0)*(x-t0)))*vectRelDensFunc(C=1,g0=g0,a=a,tEm=tEm,t=x)}, lower = t0, upper = 365)$value,integrate(function(x){(1-exp(-((beta*hostDens)+g0)*(x-t0)))*vectRelDensFunc(C=1,g0=g0,a=a,tEm=tEm,t=x)}, lower = t0, upper = 365)$value))

hvBeta <- beta # acquisiton rate
alphaA <- alpha*A2

totYears <- 5 # total number of years to make predictions for
initDensInfHost <-  hostDens*0.001 # start with a prevalence of 0.1%

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 and visualising model predictions -----
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
if(saveOutput==1){
  ggsave(paste0("plots/02_modelPreds_",plotName,".png"),fig3Plots,width=15,height=20)
  ggsave(paste0("plots/02_modelPreds_",plotName,".eps"),fig3Plots,width=15,height=20)
}

##### Estimating the value of sampling hosts or vectors -----

peakSampRat <- hostDens*hvBeta/g0 # analytic estimate of the initial vect:host prev ratio if sample vectors at peak time.
selYear <- 1 # which year to estimate the prevalence ratio from the model itself (1 will be equivalent to peakSampRat)
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 # model-derived estimate of the peak prevalence ratio
peakSampRat # analytic estimate of the peak prevalence ratio

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])


hvSampSize <- ggplot(data=filter(prevNoDetSampSize,sampSize<maxSampSizeHV),aes(x=sampSize, y=prev, colour=group)) +
  geom_line(lwd=2) +
  geom_hline(yintercept = maxPrev, lwd=2,lty=2) +
  geom_vline(xintercept = prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="host" & prevNoDetSampSize$prev<maxPrev)][1], lwd=2,lty=2) +
  geom_vline(xintercept = prevNoDetSampSize$sampSize[which(prevNoDetSampSize$group=="vect" & prevNoDetSampSize$prev<maxPrev)][1], lwd=2,lty=2) +
  labs(y = "Maximum true host prevalence", x = "Number sampled") + ylim(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))

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

hostElisaCost <- (15+10)/2 # mean cost of using ELISA per tree (ignoring transportation costs)
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))

hvSampCost <- ggplot(data=filter(prevNoDetSampCost,group=="hostVis" | group=="vectPcrSing" |group=="vectPcrPool") ,aes(x=sampCost, y=prev, colour=group)) +
  geom_line(lwd=2) +
  geom_hline(yintercept = maxPrev, lwd=2,lty=2) +
  geom_vline(xintercept = prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="hostVis" & prevNoDetSampCost$prev<maxPrev)][1], lwd=2,lty=2) +
  geom_vline(xintercept = prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="vectPcrSing" & prevNoDetSampCost$prev<maxPrev)][1], lwd=2,lty=2) +
  geom_vline(xintercept = prevNoDetSampCost$sampCost[which(prevNoDetSampCost$group=="vectPcrPool" & prevNoDetSampCost$prev<maxPrev)][1], lwd=2,lty=2) +
  labs(y = "Maximum true host prevalence", x = "Sampling costs (Euro)") +
  ylim(c(0,maxPrevAxis)) +
  xlim(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))


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
if(saveOutput==1){
  ggsave(paste0("plots/03_surveillancePlots_",plotName,".png"),fig6Plots,width=15,height=20)
  ggsave(paste0("plots/03_surveillancePlots_",plotName,".eps"),fig6Plots,width=15,height=20)
}