/
cs1_vignette.Rmd
555 lines (461 loc) · 28 KB
/
cs1_vignette.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
---
title: 'Paper case study 1: serosolver'
csl: plos.csl
output: rmarkdown::html_vignette
editor_options:
chunk_output_type: console
subttitle: Inferring pandemic A/H1N1 attack rates using longitudinal serology
bibliography: vignette_references.bib
vignette: |
%\VignetteIndexEntry{Serosolver Case Study 1}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
echo=TRUE,
comment = "#>",
eval=TRUE
)
```
# Overview
This vignette provides all of the analyses for case study 1 in the accompanying package and paper. Briefly, the first case study aims to 1) reconstruct the unobserved infection dynamics from measured titres collected several months apart, 2) examine these infection dynamics stratified by available demographic variables, such as vaccination status and age, and 3) estimate biological parameters shaping the short-term antibody response. All of the functions used here are well documented and have many tunable arguments, and we therefore encourage users to refer to the helps files.
This vignette demonstrates only how to reproduce the MCMC chains, simulate data, assess model fits and assess chain convergence. Code to reproduce figures from the main text in the accompanying paper can be found in the [`inst/extdata/scripts`](https://github.com/seroanalytics/serosolver/tree/master/inst/extdata/scripts) folder of the package.
# Setup
## Installation and requirements
`serosolver` may be installed from github using the `devtools` package. There are a number of additional packages that we need for this analysis.
```{r message=FALSE, warning=FALSE, r,eval=TRUE}
# Required to run serosolver
devtools::install_github("seroanalytics/serosolver")
library(serosolver)
library(plyr)
library(data.table)
## Required for this analysis
library(reshape2)
library(foreach)
library(doParallel)
library(bayesplot)
library(coda)
library(ggplot2)
library(viridis)
library(ggpubr)
# set up cluster
set.seed(0)
cl <- makeCluster(5)
## Note that this vignette was generated on a Windows machine,
## and the setup for parallelisation is different on a Linux or Mac:
if(Sys.info()[["sysname"]]=="Darwin" | Sys.info()[["sysname"]]=="Linux"){
library(doMC)
library(doRNG)
registerDoMC(cores=5)
}else{
registerDoParallel(cl)
}
```
## Assumptions
In this analysis, serological samples were taken between 2009 and 2012 and therefore all time variables are relative to this time period. We are interested in inferring infections and attack rates at a quarterly resolution, and therefore set `resolution` to 4. Our primary outcome of interest is to infer unbiased attack rates, and we therefore use the version of the code with a beta prior on per-time attack rates, `prior_version=2`. We set these parameters at the start of the analysis. Additionally, we assume that the samples are tested against the same virus.
```{r, eval=TRUE,}
filename <- "case_study_1"
resolution <- 4 ## set to 4 for quarterly resolution
sample_years <- 2009:2012
serosolver::describe_priors()
prior_version <- 2
```
## Preparing the data
The data used in this analysis are haemagglutination inhibition (HI) titres against A/H1N1pdm09 that began circulating in 2009. The raw data have been pre-processed to both convert them into a form usable for `serosolver` and to separate the data into vaccinated and unvaccinated data sets. Given that this analysis uses titres from a single virus it is not necessary to define an antigenic map.
```{r}
## Read in titre data
# unvaccinated
input_dat_path <- system.file("extdata", "HKdata_h1n1_unvac.csv", package = "serosolver")
input_dat <- read.csv(file = input_dat_path, header = TRUE)
# vaccinated
# input_dat_path2 <- system.file("extdata", "HKdata_h1n1_vac.csv", package = "serosolver")
# input_dat_vac <- read.csv(file = input_dat_path2, header = TRUE)
indivs <- unique(input_dat$individual) #all individuals
# Subset data for indivs
titre_dat <- input_dat[input_dat$individual %in% indivs,
c("individual","virus","titre","samples","DOB")]
titre_dat$individual <- match(titre_dat$individual, indivs)
titre_dat <- unique(titre_dat)
titre_dat <- plyr::ddply(titre_dat,.(individual,virus,samples),
function(x) cbind(x,"run"=1:nrow(x),"group"=1))
print(head(titre_dat))
strain_isolation_times <- seq(sample_years[1]*resolution+1, sample_years[4]*resolution, by=1)
```
NOTE: vaccinated and unvaccinated data are run separately in this vignette.
Finally, we must specify the `par_tab` data frame, which controls which parameters are included in the model, which are fixed, and their uniform prior ranges. Given that we are integrating out the probability of infection terms under prior version 2, we must remove these parameters from `par_tab`. Furthermore, we remove parameters relating to cross-reactivity (as we are interested in only a single-strain) and antigenic seniority (as the timescale is short). We set alpha and beta to 1/3 to define the beta prior on attack rates.
```{r}
par_tab_path <- system.file("extdata", "par_tab_base.csv", package = "serosolver")
par_tab <- read.csv(par_tab_path, stringsAsFactors=FALSE)
## Set parameters for beta and alpha to 1
par_tab[par_tab$names %in% c("alpha","beta"),"values"] <- c(1/3,1/3)
## Maximum recordable log titre in these data is 9
par_tab[par_tab$names == "MAX_TITRE","values"] <- 9
## Remove phi parameters, as these are integrated out under prior version 2
par_tab <- par_tab[par_tab$names != "phi",]
## Fix cross reactivity and antigenic seniority
par_tab[par_tab$names %in% c("tau","sigma1","sigma2"),"fixed"] <- 1
## mu, tau, sigma1, and sigma2 are fixed
par_tab[par_tab$names %in% c("tau","sigma1","sigma2"),"values"] <- 0
## set these values to 0
```
## Summary
+ Choose resolution, attack rate priors and reference time for "the present"
+ Read in titre data and convert into a useable form for `serosolver`
+ Generate antigenic map for the exposing virus (if needed)
+ Generate parameter control table for MCMC
# Running the MCMC
We are now ready to fit our model. We will fit multiple chains in parallel, though the below analysis could easily be replicated by running chains sequentially. Starting conditions for the MCMC chain must be generated that return a finite likelihood. The user may modify many of the MCMC control parameters, though the defaults are fine for most purposes.
Changing the number of iterations and the length of the adaptive period are often desirable. Crucially, the amount of chain thinning should be specified to ensure that users are not saving a large number of MCMC iterations (as this will rapidly fill disk space!). Thinning should be set such that at least 1000 iterations are saved (i.e., `iterations`/`thin` and `thin_inf_hist`). Users are encouraged to pay extra attention to `thin_inf_hist`, which dictates the thinning of the infection history chain, and can generate a very large file if left unchecked.
```{r Run mcmc setup, eval=TRUE, include=TRUE}
## Distinct filename for each chain
no_chains <- 5
filenames <- paste0(filename, "_",1:no_chains)
chain_path <- sub("par_tab_base.csv","",par_tab_path)
chain_path_real <- paste0(chain_path, "cs1_real/")
chain_path_sim <- paste0(chain_path, "cs1_sim/")
## Create the posterior solving function that will be used in the MCMC framework
par_tab[par_tab$names == "mu_short","lower_bound"] <- 1
model_func <- create_posterior_func(par_tab=par_tab,
titre_dat=titre_dat,
strain_isolation_times = strain_isolation_times,
version=prior_version) # function in posteriors.R
```
```{r Run mcmc real, eval=FALSE, include=TRUE}
## Generate results in parallel
res <- foreach(x = filenames, .packages = c('serosolver','data.table','plyr')) %dopar% {
## Not all random starting conditions return finite likelihood, so for each chain generate random
## conditions until we get one with a finite likelihood
start_prob <- -Inf
while(!is.finite(start_prob)){
## Generating starting antibody kinetics parameters
start_tab <- generate_start_tab(par_tab)
## Generate starting infection history
start_inf <- setup_infection_histories_titre(titre_dat, strain_isolation_times,
space=3,titre_cutoff=4)
start_prob <- sum(model_func(start_tab$values, start_inf)[[1]])
}
res <- serosolver(par_tab = start_tab,
titre_dat = titre_dat,
antigenic_map = NULL,
strain_isolation_times = strain_isolation_times,
start_inf_hist = start_inf,
mcmc_pars = c("iterations"=2000000,"target_acceptance_rate_theta"=0.44,"target_acceptance_rate_inf_hist"=0.44,
"adaptive_frequency"=1000,"thin"=1,"adaptive_iterations"=500000,
"save_block"=1000, "thin_inf_hist"=100,"proposal_inf_hist_indiv_prop"=1,
"proposal_ratio"=2, "burnin"=0, "proposal_inf_hist_time_prop"=0.5,
"proposal_inf_hist_distance"=3,"proposal_inf_hist_adaptive"=1,"proposal_inf_hist_indiv_swap_ratio"=0.5,
"proposal_inf_hist_group_swap_ratio"=0.5,"proposal_inf_hist_group_swap_prop"=1),
filename = paste0(chain_path_real,x),
CREATE_POSTERIOR_FUNC = create_posterior_func,
version = prior_version)
}
```
# Post-run analyses
Once the MCMC chains are run, `serosolver` provides a number of simple functions to generate standard outputs and MCMC diagnostics. The saved MCMC chains are compatible with the `coda` and `bayesplot` packages, and users are encouraged to use these.
First, read in the MCMC chains. The below function distinguishes between posterior samples for the infection history matrix and for the antibody kinetics parameters. The function searches for all files with the filenames generated by `serosolver` in the specified directory, and returns data structures with these concatenated and separated in a list.
```{r message=FALSE, warning=FALSE}
## Read in the MCMC chains
# Note that `thin` here is in addition to any thinning done during the fitting
# Chain length values in load function need to be consistent with MCMC run
#all_chains <- load_mcmc_chains(location=chain_path_real,thin=100,burnin=500000,
# par_tab=par_tab,unfixed=FALSE,convert_mcmc=TRUE)
## Alternative, load the included MCMC chains rather than re-running
data(cs1_chains_real)
all_chains <- cs1_chains_real
print(summary(all_chains))
```
Chains should then be checked for the usual MCMC diagnostics: $\hat{R}$ and effective sample size. First, looking at the antibody kinetics parameters:
```{r fig.height=6, fig.width=8}
## Get the MCMC chains as a list
list_chains <- all_chains$theta_list_chains
## Look at diagnostics for the free parameters
list_chains1 <- lapply(list_chains, function(x) as.mcmc(x[,c("mu","mu_short", "wane",
"error", "total_infections",
"lnlike", "prior_prob")]))
## Gelman-Rubin diagnostics to assess between-chain convergence for each parameter
print(gelman.diag(as.mcmc.list(list_chains1)))
gelman.plot(as.mcmc.list(list_chains1))
## Effective sample size for each parameter
print(effectiveSize(as.mcmc.list(list_chains1)))
## Posterior estimates for each parameter
print(summary(as.mcmc.list(list_chains1)))
## Plot the MCMC trace using the `bayesplot` package
color_scheme_set("viridis")
p_theta_trace <- mcmc_trace(list_chains1)
print(p_theta_trace)
```
and at the infection histories:
```{r fig.height=5, fig.width=7}
## Need to adjust x-axis label, as working with quarters not years
x_breaks <- c(strain_isolation_times[seq(1,12,by=2)],8051)
x_labels <- c("Q1-2009","Q3-2009",
"Q1-2010","Q3-2010",
"Q1-2011","Q3-2011",
"Prior")
x_breaks2 <- strain_isolation_times[seq(1,12,by=4)]
x_labels2 <- c("Q1-2009","Q1-2010","Q1-2011")
x_axis <- scale_x_continuous(breaks=x_breaks, labels=x_labels)
x_axis2 <- scale_x_continuous(breaks=x_breaks2, labels=x_labels2)
## Extract infection history chain
inf_chain <- all_chains$inf_chain
## Look at inferred attack rates
## Green shows times that serum samples were taken
p_ar <- plot_attack_rates(inf_chain, titre_dat, strain_isolation_times, pad_chain=TRUE,
plot_den = TRUE,prior_pars=list(prior_version=prior_version,
alpha=par_tab[par_tab$names=="alpha","values"],
beta=par_tab[par_tab$names=="beta","values"])) + x_axis
print(p_ar)
## Calculate convergence diagnostics and summary statistics on infection histories
## Important to scale all infection estimates by number alive from titre_dat
n_alive <- get_n_alive_group(titre_dat, strain_isolation_times,melt=TRUE)
## This function generates a number of MCMC outputs
ps_infhist <- plot_posteriors_infhist(inf_chain=inf_chain,
years=strain_isolation_times,
samples = 100,
## Needs to be smaller than length of sampled chain
n_alive=n_alive)
## Posterior mean, median, 95% credible intervals and effective sample size
## on per time attack rates
print(head(ps_infhist[["estimates"]]$by_year))
## Posterior mean, median, 95% credible intervals and effective sample size
## on per individual total number of infections
print(head(ps_infhist[["estimates"]]$by_indiv))
## Check for agreement between inferred cumulative infection histories
## for some individuals
p_indiv_inf_hists <- generate_cumulative_inf_plots(inf_chain, indivs=1:9, pad_chain=FALSE,
nsamp = 100,
## Needs to be smaller than length of sampled chain
strain_isolation_times = strain_isolation_times,
number_col=3)
p1 <- p_indiv_inf_hists[[1]] + x_axis2
## Each subplot shows cumulative number of infections
## over time for an individual. Colours show estimates
## from different MCMC chains.
print(p1)
## Posterior probability that infections occured at given times per individual
p2 <- p_indiv_inf_hists[[2]] + x_axis2
## Each subplot shows posterior density of infection
## occuring in each quarter for a single individual
print(p2)
```
One of the MCMC chains (chain 2) does not apepar to converge to the same distribution as the others until the second half of MCMC iterations, but the 5 chains do appear to converge to the same posterior distribution and give high effective sample sizes for all parameters. $\hat{R}$ is also $<1.1$ for all parameters.
Users may also easily check the inferred antibody landscapes at the time each sample was taken. Black dots show observations, shaded regions and dashed lines show 95% credible intervals on assay measurements (light) and latent true antibody levels (dark) and posterior median.
```{r fig.height=5, fig.width=7}
## get_titre_predictions expects only a single MCMC chain, so
## subset for only one chain
chain <- as.data.frame(all_chains$theta_chain)
chain1 <- chain[chain$chain_no == 1,]
inf_chain1 <- inf_chain[inf_chain$chain_no == 1,]
rand_indivs <- c(2,21,36,195)
x_labels <- c("2009-Q1","2009-Q2","2009-Q3","2009-Q4",
"2010-Q1","2010-Q2","2010-Q3","2010-Q4",
"2011-Q1","2011-Q2","2011-Q3","2011-Q4")
titre_p <- plot_infection_histories(chain = chain1,
infection_histories = inf_chain1,
titre_dat = titre_dat,
individuals = rand_indivs,
strain_isolation_times = strain_isolation_times,
nsamp = 100, # Needs to be smaller than length of sampled chain
par_tab = par_tab) +
scale_x_continuous(expand=c(0,0),labels=x_labels[seq(1,12,by=2)],
breaks=strain_isolation_times[seq(1,12,by=2)])
print(titre_p)
```
# Simulation recovery
We finish the vignette by presenting a simulation-recovery experiment to test the ability of the framework to recover known infection histories and antibody kinetics parameters using simulated data that matches the real dataset.
## Extract attack rates from fits
We simulate infection histories and antibody titre data based on the "real" parameters inferred from fitting the model above. First, we extract the maximum posterior probability antibody kinetics parameters and attack rates.
```{r message=FALSE, warning=FALSE}
## Read in MCMC chains from fitting
#all_chains <- load_mcmc_chains(location=chain_path_real,thin=100,burnin=500000,
# par_tab=par_tab,unfixed=FALSE,convert_mcmc=FALSE)
## Alternative, load the included MCMC chains rather than re-running
data(cs1_chains_real_b)
all_chains <- cs1_chains_real_b
## Find samples that were in both theta and inf hist chains
chain <- all_chains$theta_chain
inf_chain <- all_chains$inf_chain
intersect_samps <- intersect(unique(inf_chain$samp_no), unique(chain$samp_no))
chain <- chain[chain$samp_no %in% intersect_samps,]
## Find the parameter values that gave the highest posterior probability
which_mle <- chain[which.max(chain$lnlike),c("samp_no","chain_no")]
mle_theta_pars <- chain[chain$samp_no == which_mle$samp_no & chain$chain_no == which_mle$chain_no,]
## Store total infections to compare later
mle_total_infs <- mle_theta_pars[,"total_infections"]
mle_theta_pars <- mle_theta_pars[,par_tab$names]
mle_inf_hist <- inf_chain[inf_chain$samp_no == which_mle$samp_no &
inf_chain$chain_no == which_mle$chain_no,]
## Generate full infection history matrix using provided function
mle_inf_hist <- expand_summary_inf_chain(mle_inf_hist[,c("samp_no","j","i","x")])
## Find number of infections per year from this infection history
no_infs <- colSums(mle_inf_hist[,3:ncol(mle_inf_hist)])
## If missing time points in simulated attack rates
if(length(no_infs) < length(strain_isolation_times)){
diff_lengths <- length(strain_isolation_times) - length(no_infs)
no_infs <- c(no_infs, rep(0, diff_lengths))
}
## Find attack rate per year
n_alive <- get_n_alive(titre_dat, strain_isolation_times)
attack_rates <- no_infs/n_alive
```
Functions are provided to simulate antibody titre data under a given serosurvey design. The antibody kinetics parameters and attack rates estimated above are used to simulate titres from the model. The `simulate_data` function is well documented, and users should refer to the help file to customise the simulated serosurvey design.
```{r fig.height=6, fig.width=8}
set.seed(0)
sim_par_tab <- par_tab
sim_par_tab$values <- as.numeric(mle_theta_pars)
sim_par_tab <- sim_par_tab[sim_par_tab$names != "phi",]
sim_par_tab[sim_par_tab$names %in% c("alpha","beta"),"values"] <- c(1/3,1/3)
sim_par_tab[sim_par_tab$names %in% c("tau","sigma1","sigma2"),"fixed"] <- 1
sim_par_tab[sim_par_tab$names %in% c("tau","sigma1","sigma2"),"values"] <- 0
sim_par_tab[sim_par_tab$names == "MAX_TITRE","values"] <- 9
sampling_times <- seq(2009*resolution + 1, 2012*resolution, by=1)
age_min <- 6*resolution
age_max <- 6*resolution
n_indiv <- length(unique(titre_dat$individual))
dat <- simulate_data(par_tab = sim_par_tab,
n_indiv = n_indiv,
buckets = resolution,
strain_isolation_times = strain_isolation_times,
measured_strains = min(strain_isolation_times),
sampling_times = sampling_times,
nsamps = 4,
antigenic_map = NULL,
age_min = age_min,
age_max = age_max,
attack_rates=attack_rates,
repeats = 1)
## Inspect simulated antibody titre data and infection histories
sim_titre_dat <- dat[["data"]]
sim_infection_histories <- dat[["infection_histories"]]
## Store total infections to compare later
actual_total_infections <- sum(sim_infection_histories)
## Red lines show times of infection
## Note that x-axis shows quarters (ie. year*4)
plot_data(sim_titre_dat, sim_infection_histories, strain_isolation_times,
n_indivs = 16,study_design="single_strain")
sim_ages <- dat[["ages"]]
sim_titre_dat <- merge(sim_titre_dat, sim_ages)
sim_ar <- dat[["attack_rates"]]
```
## Simulation fitting
Once these simulated data have been generated, the work flow becomes exactly the same as with the real data above.
```{r Run mcmc sim setup, eval=TRUE, include=TRUE}
filename <- "case_study_1_sim"
## Distinct filename for each chain
no_chains <- 5
filenames <- paste0(filename, "_",1:no_chains)
## Create the posterior solving function that will be used in the MCMC framework
model_func <- create_posterior_func(par_tab=sim_par_tab,
titre_dat=sim_titre_dat,
antigenic_map=NULL,
strain_isolation_times = strain_isolation_times,
version=prior_version) # function in posteriors.R
```
```{r Run mcmc sim, eval=FALSE, include=TRUE}
## Generate results in parallel
res <- foreach(x = filenames, .packages = c('serosolver','data.table','plyr')) %dopar% {
## Not all random starting conditions return finite likelihood, so for each chain generate random
## conditions until we get one with a finite likelihood
start_prob <- -Inf
while(!is.finite(start_prob)){
## Generate starting values for theta
start_tab <- generate_start_tab(sim_par_tab)
## Generate starting infection history
start_inf <- setup_infection_histories_titre(sim_titre_dat, strain_isolation_times,
space=3,titre_cutoff=4)
start_prob <- sum(model_func(start_tab$values, start_inf)[[1]])
}
res <- serosolver(par_tab = start_tab,
titre_dat = sim_titre_dat,
antigenic_map = NULL,
strain_isolation_times = strain_isolation_times,
start_inf_hist = start_inf,
mcmc_pars = c("iterations"=1000000,"target_acceptance_rate_theta"=0.44,"target_acceptance_rate_inf_hist"=0.44,
"adaptive_frequency"=1000,"thin"=100,"adaptive_iterations"=200000,
"save_block"=1000, "thin_inf_hist"=1000,"proposal_inf_hist_indiv_prop"=0.5,
"proposal_ratio"=2, "burnin"=0, "proposal_inf_hist_time_prop"=1,
"proposal_inf_hist_distance"=3,"proposal_inf_hist_adaptive"=1,"proposal_inf_hist_indiv_swap_ratio"=0.5,
"proposal_inf_hist_group_swap_ratio"=0.5,"proposal_inf_hist_group_swap_prop"=1),
filename = paste0(chain_path_sim,x),
CREATE_POSTERIOR_FUNC = create_posterior_func,
version = prior_version)
}
```
## Simulation analysis
MCMC chains should be checked for convergence under the usual diagnostics. We also compare the inferred posterior distributions to the known true parameter values. We see that convergence and between-chain agreement is good and that the model recovers reasonably unbiased estimates for the parameters. Biases in inference may be driven by the contribution of the attack rate prior relative to the contribution of the likelihood (the data). Increasing the number of measured titres (for example, measure titres against 40 viruses rather than 9 or 6 serum samples rather than 4) or using a more informative attack rate prior would help reduce such bias.
```{r message=FALSE, warning=FALSE, fig.height=4, fig.width=6}
## Read in the MCMC chains
## Note that `thin` here is in addition to any thinning done during the fitting
#sim_all_chains <- load_mcmc_chains(location=chain_path_sim,thin=10,burnin=200000,
# par_tab=par_tab,unfixed=FALSE,convert_mcmc=TRUE)
## Alternative, load the included MCMC chains rather than re-running
data(cs1_chains_sim)
sim_all_chains <- cs1_chains_sim
theta_chain <- sim_all_chains$theta_chain
## Get the MCMC chains as a list
list_chains <- sim_all_chains$theta_list_chains
## Look at diagnostics for the free parameters
list_chains1 <- lapply(list_chains, function(x) as.mcmc(x[,c("mu","mu_short","wane",
"error","total_infections",
"lnlike","prior_prob")]))
## Gelman-Rubin diagnostics and effective sample size
print(gelman.diag(as.mcmc.list(list_chains1)))
print(effectiveSize(as.mcmc.list(list_chains1)))
melted_theta_chain <- reshape2::melt(as.data.frame(theta_chain), id.vars=c("samp_no","chain_no"))
estimated_pars <- c(sim_par_tab[sim_par_tab$fixed == 0,"names"],"total_infections")
melted_theta_chain <- melted_theta_chain[melted_theta_chain$variable %in% estimated_pars,]
colnames(melted_theta_chain)[3] <- "names"
add_row <- data.frame("total_infections",actual_total_infections,0,0.1,0,10000,0,0,1)
colnames(add_row) <- colnames(sim_par_tab)
sim_par_tab1 <- rbind(sim_par_tab, add_row)
ggplot(melted_theta_chain) +
geom_density(aes(x=value,fill=as.factor(chain_no)),alpha=0.5) +
geom_vline(data=sim_par_tab1[sim_par_tab1$fixed == 0,],aes(xintercept=values),linetype="dashed") +
facet_wrap(~names,scales="free") +
theme_classic() +
theme(legend.position="bottom")
```
Recovery of known attack rates is also reasonably accurate. Again, more titre data or more individuals would improve inferential power if lacking. One particularly reassuring plot is the comparison of known individual cumulative infection histories (the cumulative sum of infections over time for an individual) against the estimated posterior distribution of cumulative infection histories. We see that the 95% credible intervals capture the true cumulative infection histories in almost all cases.
```{r fig.height=5, fig.width=8}
## Extract infection history chain
inf_chain <- sim_all_chains$inf_chain
## Look at inferred attack rates
## Green shows times that serum samples were taken
p_ar <- plot_attack_rates(inf_chain, sim_titre_dat, strain_isolation_times, pad_chain=TRUE,
plot_den = TRUE,prior_pars=list(prior_version=prior_version,
alpha=par_tab[par_tab$names=="alpha","values"],
beta=par_tab[par_tab$names=="beta","values"])) +
geom_point(data=sim_ar,aes(x=year,y=AR),col="purple") +
x_axis
print(p_ar)
## Calculate convergence diagnostics and summary statistics on infection histories
## Important to scale all infection estimates by number alive from titre_dat
sim_n_alive <- get_n_alive_group(sim_titre_dat, strain_isolation_times,melt=TRUE)
## This function generates a number of MCMC outputs
ps_infhist <- plot_posteriors_infhist(inf_chain=inf_chain,
years=strain_isolation_times,
n_alive=sim_n_alive,
pad_chain=TRUE)
## Check for agreement between inferred cumulative infection histories
## for some individuals
p_indiv_inf_hists <- generate_cumulative_inf_plots(inf_chain,
indivs=sample(which(rowSums(sim_infection_histories) > 0),9),
pad_chain=TRUE,
real_inf_hist=sim_infection_histories,
strain_isolation_times = strain_isolation_times,
number_col=3)
p1 <- p_indiv_inf_hists[[1]] + x_axis2
## Each subplot shows cumulative number of infections
## over time for an individual. Colours show estimates
## from different MCMC chains.
## Blue lines show true cumulative infection histories
print(p1)
## Posterior probability that infections occured at given times per individual
## Each subplot shows posterior density of infection
## occuring in each quarter for a single individual
## Vertical red lines show timing of true infections
p2 <- p_indiv_inf_hists[[2]] + x_axis2
print(p2)
```