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 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.

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.

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.

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.

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_hist). Users are encouraged to pay extra attention to thin_hist, which dictates the thinning of the infection history chain, and can generate a very large file if left unchecked.

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 run_MCMC in the specified directory, and returns data structures with these concatenated and separated in a list.

Chains should then be checked for the usual MCMC diagnostics: \(\hat{R}\) and effective sample size. First, looking at the antibody kinetics parameters:

and at the infection histories:


## 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)
#> Padding inf chain...
#> Done
#> Calculating by time summaries...
#> Done
#> Calculating by individual summaries...
#> Done


## Posterior mean, median, 95% credible intervals and effective sample size
## on per time attack rates
print(head(ps_infhist[["estimates"]]$by_year))
#>       j group       mean     median lower_quantile upper_quantile
#> 1: 8037     1 0.06270025 0.06188925    0.048859935     0.07491857
#> 2: 8038     1 0.01469070 0.01302932    0.000000000     0.03257329
#> 3: 8039     1 0.01654092 0.01628664    0.009771987     0.02605863
#> 4: 8040     1 0.05514637 0.05537459    0.048859935     0.06188925
#> 5: 8041     1 0.05396715 0.05537459    0.022801303     0.08143322
#> 6: 8042     1 0.03463024 0.03257329    0.000000000     0.09120521
#>    effective_size gelman_point gelman_upper
#> 1:      2704.5912     1.010573     1.027657
#> 2:       680.0930     1.012581     1.033547
#> 3:       482.6676     1.017627     1.043147
#> 4:      4530.5617     1.000146     1.000453
#> 5:      2860.5229     1.003968     1.011721
#> 6:      1596.7841     1.007542     1.021552

## Posterior mean, median, 95% credible intervals and effective sample size
## on per individual total number of infections
print(head(ps_infhist[["estimates"]]$by_indiv))
#>    i     mean median lower_quantile upper_quantile effective_size
#> 1: 1 2.000100      2              2              2      10005.000
#> 2: 2 1.999600      2              2              2      10005.000
#> 3: 3 2.000100      2              2              2      10005.000
#> 4: 4 1.933233      2              1              2       7555.554
#> 5: 6 1.001699      1              1              1      10005.000
#> 6: 7 1.951524      2              1              2       7525.574

## 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) 

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.

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.

## 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)
#> Chains detected:     5Highest MCMC sample interations: 
#> Chains detected: 
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_real//case_study_1_test_1_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_real//case_study_1_test_2_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_real//case_study_1_test_3_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_real//case_study_1_test_4_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_real//case_study_1_test_5_infection_histories.csv
#> [[1]]
#> [1] 290430
#> 
#> [[2]]
#> [1] 291565
#> 
#> [[3]]
#> [1] 290447
#> 
#> [[4]]
#> [1] 289656
#> 
#> [[5]]
#> [1] 290215

## 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$sampno), unique(chain$sampno))
chain <- chain[chain$sampno %in% intersect_samps,]

## Find the parameter values that gave the highest posterior probability
which_mle <- chain[which.max(chain$lnlike),c("sampno","chain_no")]
mle_theta_pars <- chain[chain$sampno == which_mle$sampno & 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$sampno == which_mle$sampno & 
                            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("sampno","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.

Simulation fitting

Once these simulated data have been generated, the work flow becomes exactly the same as with the real data above.

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.

## 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)
#> Chains detected:     5Highest MCMC sample interations: 
#> Chains detected: 
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_sim//case_study_1_sim_1_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_sim//case_study_1_sim_2_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_sim//case_study_1_sim_3_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_sim//case_study_1_sim_4_infection_histories.csv
#> X:/Program Files/R/R-3.6.2/library/serosolver/extdata/cs1_sim//case_study_1_sim_5_infection_histories.csv
#> [[1]]
#> [1] 13391
#> 
#> [[2]]
#> [1] 13379
#> 
#> [[3]]
#> [1] 13406
#> 
#> [[4]]
#> [1] 13412
#> 
#> [[5]]
#> [1] 13416

## 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) 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)))
#> Potential scale reduction factors:
#> 
#>                  Point est. Upper C.I.
#> mu                     1.01       1.04
#> mu_short               1.00       1.02
#> wane                   1.02       1.07
#> error                  1.00       1.01
#> total_infections       1.01       1.04
#> lnlike                 1.01       1.03
#> prior_prob             1.00       1.01
#> 
#> Multivariate psrf
#> 
#> 1.03
print(effectiveSize(as.mcmc.list(list_chains1)))
#>               mu         mu_short             wane            error 
#>         619.5195         645.0542         457.5725         605.7508 
#> total_infections           lnlike       prior_prob 
#>         562.9334         422.0668         539.8325

melted_theta_chain <- reshape2::melt(as.data.frame(theta_chain), id.vars=c("sampno","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.