Introduction
The serodynamics package provides tools for modeling longitudinal antibody responses to infection using Bayesian MCMC methods. This vignette demonstrates the main workflow for:
- Loading or simulating case data
- Preparing data for MCMC analysis
- Running the Bayesian model
- Visualizing and interpreting results
Installation
First, ensure you have JAGS installed on your system (required for Bayesian MCMC):
-
Ubuntu/Linux:
sudo apt-get install jags - macOS: Download from JAGS website
- Windows: Download from JAGS website
Then install the package. The examples below require the development version, so install that:
# install.packages("pak")
pak::pak("UCD-SERG/serodynamics")A released version is also available on CRAN:
install.packages("serodynamics")The released version uses an older set of function names, listed below for reference. Renaming calls is not enough to run this article on the released version.
| This article | Released version |
|---|---|
run_serodynamics() |
run_mod() |
plot_trace() |
plot_jags_trace() |
plot_density() |
plot_jags_dens() |
plot_rhat() |
plot_jags_Rhat() |
plot_ess() |
plot_jags_effect() |
summarize_posterior() |
post_summ() |
Load Required Libraries
Example 1: Using Existing Data
The package includes example data from the SEES Typhoid study in Nepal:
data(nepal_sees)
head(nepal_sees)
#> # A tibble: 6 × 9
#> Country id sample_id bldculres antigen_iso studyvisit dayssincefeveronset
#> <chr> <chr> <chr> <chr> <chr> <chr> <dbl>
#> 1 Nepal sees_n… N000_122 typhi HlyE_IgA 28_days 40
#> 2 Nepal sees_n… N000_122 typhi HlyE_IgG 28_days 40
#> 3 Nepal sees_n… N000_297 typhi HlyE_IgA 3_months 135
#> 4 Nepal sees_n… N000_297 typhi HlyE_IgG 3_months 135
#> 5 Nepal sees_n… N000_372 typhi HlyE_IgA 6_months 171
#> 6 Nepal sees_n… N000_372 typhi HlyE_IgG 6_months 171
#> # ℹ 2 more variables: result <dbl>, visit_num <int>Prepare the Data
Convert the data to a case_data object (nepal_sees already is a case_data object, but we can reconvert it just to demonstrate).
case_data <- as_case_data(
nepal_sees,
id_var = "id",
time_in_days = "dayssincefeveronset",
value_var = "result",
biomarker_var = "antigen_iso"
)
# View the structure
head(case_data)
#> # A tibble: 6 × 9
#> Country id sample_id bldculres antigen_iso studyvisit dayssincefeveronset
#> <chr> <chr> <chr> <chr> <chr> <chr> <dbl>
#> 1 Nepal sees_n… N000_122 typhi HlyE_IgA 28_days 40
#> 2 Nepal sees_n… N000_122 typhi HlyE_IgG 28_days 40
#> 3 Nepal sees_n… N000_297 typhi HlyE_IgA 3_months 135
#> 4 Nepal sees_n… N000_297 typhi HlyE_IgG 3_months 135
#> 5 Nepal sees_n… N000_372 typhi HlyE_IgA 6_months 171
#> 6 Nepal sees_n… N000_372 typhi HlyE_IgG 6_months 171
#> # ℹ 2 more variables: result <dbl>, visit_num <int>Visualize the Raw Data
autoplot(case_data)
Example 2: Simulating Data
You can also simulate case data using antibody curve parameters:
set.seed(123)
# Use typhoid curve parameters from serocalculator
simulated_data <- sim_case_data(
n = 50, # Number of cases to simulate
curve_params = serocalculator::typhoid_curves_nostrat_100,
max_n_obs = 6, # Maximum observations per case
followup_interval = 14 # Days between follow-up visits
)
head(simulated_data)
#> # A tibble: 6 × 11
#> id visit_num timeindays iter antigen_iso y0 y1 t1 alpha r
#> <chr> <int> <dbl> <int> <fct> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 0 89 HlyE_IgA 0.666 47.1 7.18 5.22e-4 1.56
#> 2 1 1 0 89 HlyE_IgG 3.52 266. 5.60 1.25e-3 1.53
#> 3 1 1 0 89 LPS_IgA 1.77 2071. 1.71 2.21e-5 3.45
#> 4 1 1 0 89 LPS_IgG 0.200 234. 5.30 1.69e-3 1.28
#> 5 1 1 0 89 Vi_IgG 1.66 543. 8.37 3.72e-5 1.26
#> 6 1 2 14 89 HlyE_IgA 0.666 47.1 7.18 5.22e-4 1.56
#> # ℹ 1 more variable: value <dbl>
autoplot(simulated_data)
Running the Bayesian Model
The main function run_serodynamics() fits a Bayesian MCMC model to estimate antibody dynamic curve parameters:
-
y0: Baseline antibody concentration -
y1: Peak antibody concentration
-
t1: Time to peak -
shape: Shape parameter -
alpha: Decay rate
Stratified kinetic models can be generated by specifying a covariate via the strat argument, enabling separate model fits for subgroups defined by age group, serotype, geography, or other covariates, used when kinetic parameters may vary across populations.
Priors
Specify priors explicitly, chosen to correspond to your observed data and expected trajectories, rather than relying on defaults. Because priors are placed on log-transformed parameters, the prior means in mu_hyp_param are also on the log scale. Prior specification is done through the function prep_priors(), which is built into run_serodynamics(). Five components are specified:
-
mu_hyp_param: The hyperprior means for the log-transformed population-level parameters
-
prec_hyp_param: The hyperprior precisions (inverse variances) around those means
-
omega_param: The Wishart scale matrix controlling expected between-individual variability
-
wishdf_param: The Wishart degrees of freedom
-
prec_logy_hyp_param: The gamma hyperprior on measurement precision
Users with strong external information can tighten prec_hyp_param. Users seeking more diffuse priors or facing convergence difficulties can lower prec_hyp_param and/or reduce wishdf_param (e.g. 5-10), which weakens the prior on between-individual variation.
(Priors used in below code were selected based on 1) Users should always specify priors according to their own data set.
Bayesian specification
Users specify the number of MCMC chains (nchain, 1-4), adaptation iterations (nadapt), burn-in iterations (nburn), retained samples per chain (nmc), and total iterations (niter), with thinning computed as niter/nmc. Chains are executed in parallel for computational efficiency. It is recommended that 4 chains are run concurrently for inference. Additional computing power may be necessary when running large models with many iterations.
For further information please visit: https://cran.r-project.org/package=runjags
# Note: This example uses reduced iterations for demonstration
# For actual analysis, use larger values (e.g., nmc=1000, niter=2000)
fitted_model <- run_serodynamics(
data = nepal_sees,
file_mod = serodynamics_example("model.jags"),
nchain = 4, # Number of MCMC chains
nadapt = 100, # Adaptation iterations
nburn = 100, # Burn-in iterations
nmc = 10, # Samples per chain (use 1000+ for real analysis)
niter = 20, # Total iterations (use 2000+ for real analysis)
# Priors were selected based on Aiemjoy K et al. Estimating typhoid incidence from community-based serosurveys: a multicohort study (2022).
# Users should always specify priors according to their own data set.
mu_hyp_param = c(1.0, 7.0, 1.0, -4.0, -1.0), # Prior mean for the population level parameters
prec_hyp_param = c(1.0, 0.0001, 1.0, 0.001, 1.0), # Hyperprior precision matrix
omega_param = c(1.0, 50.0, 1.0, 10.0, 1.0), # Wishart hyperprior distributions
wishdf_param = 20, # Degrees of freedom for the Wishart hyperprior distribution
prec_logy_hyp_param = c(4.0, 1.0) # Hyperprior precision matrix
)
#> Calling 4 simulations using the parallel method...
#> Following the progress of chain 1 (the program will wait for all chains
#> to finish before continuing):
#> Welcome to JAGS 5.0.2 on Wed Nov 25 01:03:19 2026
#> JAGS is free software and comes with ABSOLUTELY NO WARRANTY
#> Loading module: basemod: ok
#> Loading module: bugs: ok
#> Loading module: diag: ok
#> . . Reading data file data.txt
#> . Compiling model graph
#> Resolving undeclared variables
#> Allocating nodes
#> Graph information:
#> Fully observed stochastic nodes: 904
#> Unobserved stochastic nodes: 500
#> Total graph size: 19331
#> . Reading parameter file inits1.txt
#> . Initializing model
#> . Adaptation skipped: model is not in adaptive mode.
#> . Updating 100
#> -------------------------------------------------| 100
#> ************************************************** 100%
#> . . . . . . Updating 20
#> . . . . Updating 0
#> . Deleting model
#> . Exiting JAGS
#> All chains have finished
#> Note: the model did not require adaptation
#> Simulation complete. Reading coda files...
#> Coda files loaded successfully
#> Finished running the simulation
head(fitted_model)
#> # A tibble: 6 × 7
#> Iteration Chain Parameter Iso_type Stratification Subject value
#> <int> <int> <chr> <chr> <chr> <chr> <dbl>
#> 1 1 1 alpha HlyE_IgA None sees_npl_1 0.00108
#> 2 2 1 alpha HlyE_IgA None sees_npl_1 0.00106
#> 3 3 1 alpha HlyE_IgA None sees_npl_1 0.00386
#> 4 4 1 alpha HlyE_IgA None sees_npl_1 0.00357
#> 5 5 1 alpha HlyE_IgA None sees_npl_1 0.000527
#> 6 6 1 alpha HlyE_IgA None sees_npl_1 0.00260Model Diagnostics
After fitting the model, check convergence diagnostics:
# Trace plots to assess chain mixing
plot_trace(fitted_model)
#> $None
#> $None$HlyE_IgA
#>
#> $None$HlyE_IgG

# Density plots of posterior distributions
plot_density(fitted_model)
#> $None
#> $None$HlyE_IgA
#>
#> $None$HlyE_IgG

# Rhat statistics (values near 1.0 indicate convergence)
plot_rhat(fitted_model)
#> $None
#> $None$HlyE_IgA
#>
#> $None$HlyE_IgG

# Effective sample size
plot_ess(fitted_model)
#> $None
#> $None$HlyE_IgA
#>
#> $None$HlyE_IgG

Visualizing Fitted Curves
Plot the predicted stratified antibody curves with credible intervals:
plot_serocurve(fitted_model,
log_y = TRUE)
Plot the predicted antibody curve for an individual with their original observed data for HlyE IgA.
plot_predicted_curve(
fitted_model,
ids = serocalculator::ids(nepal_sees)[1],
antigen_iso = nepal_sees$antigen_iso[1],
dataset = nepal_sees, # Original data set to overlay raw data
log_y = TRUE # Plotting Y-axis on the log scale
)
Post-Processing Results
Extract and summarize the posterior estimates:
# Summarize parameter estimates
summary_stats <- summarize_posterior(fitted_model)
print(summary_stats)
#> # A tibble: 10 × 11
#> Iso_type Parameter Stratification Mean SD Median `2.5%` `25.0%`
#> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 HlyE_IgA alpha None 0.00195 0.00143 1.77e-3 3.12e-4 8.06e-4
#> 2 HlyE_IgA shape None 1.33 0.118 1.31e+0 1.14e+0 1.26e+0
#> 3 HlyE_IgA t1 None 3.20 1.08 3.04e+0 1.55e+0 2.49e+0
#> 4 HlyE_IgA y0 None 2.96 0.984 2.78e+0 1.48e+0 2.31e+0
#> 5 HlyE_IgA y1 None 92.6 185. 2.90e+1 3.29e+0 1.51e+1
#> 6 HlyE_IgG alpha None 0.00215 0.00208 1.54e-3 5.51e-4 9.12e-4
#> 7 HlyE_IgG shape None 1.30 0.107 1.27e+0 1.16e+0 1.22e+0
#> 8 HlyE_IgG t1 None 7.02 4.78 5.74e+0 1.52e+0 3.37e+0
#> 9 HlyE_IgG y0 None 2.67 1.51 2.41e+0 1.15e+0 2.10e+0
#> 10 HlyE_IgG y1 None 331. 468. 1.47e+2 1.57e+1 7.03e+1
#> # ℹ 3 more variables: `50.0%` <dbl>, `75.0%` <dbl>, `97.5%` <dbl>Checking model fit
Plot the residuals over time including mean absolute error (MAE):
# Plot residuals over time, annotated with mean absolute error
residuals_plot <- plot_residuals(fitted_model)
print(residuals_plot)
Working with Stratified Data
You can stratify the analysis by a grouping variable:
# Create stratified data
strat1 <- sim_case_data(
n = 30,
curve_params = serocalculator::typhoid_curves_nostrat_100
) |>
mutate(pathogen = "Typhoid")
strat2 <- sim_case_data(
n = 30,
curve_params = serocalculator::typhoid_curves_nostrat_100
) |>
mutate(pathogen = "Paratyphoid")
stratified_data <- bind_rows(strat1, strat2)
# Fit model with stratification
fitted_stratified <- run_serodynamics(
data = stratified_data,
file_mod = serodynamics_example("model.jags"),
nchain = 2,
nadapt = 100,
nburn = 100,
nmc = 10,
niter = 20,
strat = "pathogen", # Specify stratification variable
mu_hyp_param = c(1.0, 7.0, 1.0, -4.0, -1.0),
prec_hyp_param = c(1.0, 0.0001, 1.0, 0.001, 1.0),
omega_param = c(1.0, 50.0, 1.0, 10.0, 1.0),
wishdf_param = 20,
prec_logy_hyp_param = c(4.0, 1.0)
)
#> Calling 2 simulations using the parallel method...
#> Following the progress of chain 1 (the program will wait for all chains
#> to finish before continuing):
#> Welcome to JAGS 5.0.2 on Wed Nov 25 01:03:41 2026
#> JAGS is free software and comes with ABSOLUTELY NO WARRANTY
#> Loading module: basemod: ok
#> Loading module: bugs: ok
#> Loading module: diag: ok
#> . . Reading data file data.txt
#> . Compiling model graph
#> Resolving undeclared variables
#> Allocating nodes
#> Graph information:
#> Fully observed stochastic nodes: 775
#> Unobserved stochastic nodes: 185
#> Total graph size: 12303
#> . Reading parameter file inits1.txt
#> . Initializing model
#> . Adaptation skipped: model is not in adaptive mode.
#> . Updating 100
#> -------------------------------------------------| 100
#> ************************************************** 100%
#> . . . . . . Updating 20
#> . . . . Updating 0
#> . Deleting model
#> . Exiting JAGS
#> All chains have finished
#> Note: the model did not require adaptation
#> Simulation complete. Reading coda files...
#> Coda files loaded successfully
#> Finished running the simulation
#> Calling 2 simulations using the parallel method...
#> Following the progress of chain 1 (the program will wait for all chains
#> to finish before continuing):
#> Welcome to JAGS 5.0.2 on Wed Nov 25 01:03:47 2026
#> JAGS is free software and comes with ABSOLUTELY NO WARRANTY
#> Loading module: basemod: ok
#> Loading module: bugs: ok
#> Loading module: diag: ok
#> . . Reading data file data.txt
#> . Compiling model graph
#> Resolving undeclared variables
#> Allocating nodes
#> Graph information:
#> Fully observed stochastic nodes: 760
#> Unobserved stochastic nodes: 185
#> Total graph size: 12135
#> . Reading parameter file inits1.txt
#> . Initializing model
#> . Adaptation skipped: model is not in adaptive mode.
#> . Updating 100
#> -------------------------------------------------| 100
#> ************************************************** 100%
#> . . . . . . Updating 20
#> . . . . Updating 0
#> . Deleting model
#> . Exiting JAGS
#> All chains have finished
#> Note: the model did not require adaptation
#> Simulation complete. Reading coda files...
#> Coda files loaded successfully
#> Finished running the simulationNext Steps
- See the function reference for complete API documentation
- Check out example datasets:
?nepal_sees,?nepal_sees_jags_output
Session Info
sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#> setting value
#> version R version 4.6.2 (2026-10-29)
#> os Ubuntu 26.04.1 LTS
#> system x86_64, linux-gnu
#> ui X11
#> language en-US
#> collate C.UTF-8
#> ctype C.UTF-8
#> tz UTC
#> date 2026-11-25
#> pandoc 3.8.3 @ /opt/hostedtoolcache/pandoc/3.8.3/x64/ (via rmarkdown)
#> quarto 1.11.9 @ /usr/local/bin/quarto
#>
#> ─ Packages ───────────────────────────────────────────────────────────────────
#> package * version date (UTC) lib source
#> cli 3.6.6 2026-04-09 [1] CRAN (R 4.6.2)
#> coda 0.19-4.1 2024-01-31 [1] CRAN (R 4.6.2)
#> codetools 0.2-20 2024-03-31 [3] CRAN (R 4.6.2)
#> digest 0.6.39 2025-11-19 [1] CRAN (R 4.6.2)
#> doParallel 1.0.17 2022-02-07 [1] CRAN (R 4.6.2)
#> dplyr * 1.2.1 2026-04-03 [1] CRAN (R 4.6.2)
#> evaluate 1.0.5 2025-08-27 [1] CRAN (R 4.6.2)
#> farver 2.1.2 2024-05-13 [1] CRAN (R 4.6.2)
#> fastmap 1.2.0 2024-05-15 [1] CRAN (R 4.6.2)
#> foreach 1.5.2 2022-02-02 [1] CRAN (R 4.6.2)
#> fs 2.1.0 2026-04-18 [1] CRAN (R 4.6.2)
#> generics 0.1.4 2025-05-09 [1] CRAN (R 4.6.2)
#> GGally 2.5.0 2026-11-09 [1] CRAN (R 4.6.2)
#> ggmcmc 1.5.1.2 2025-10-02 [1] CRAN (R 4.6.2)
#> ggplot2 * 4.0.4 2026-11-14 [1] CRAN (R 4.6.2)
#> ggstats 0.14.0 2026-09-02 [1] CRAN (R 4.6.2)
#> glue 1.8.1 2026-04-17 [1] CRAN (R 4.6.2)
#> gtable 0.3.6 2024-10-25 [1] CRAN (R 4.6.2)
#> htmltools 0.5.9 2025-12-04 [1] CRAN (R 4.6.2)
#> iterators 1.0.14 2022-02-05 [1] CRAN (R 4.6.2)
#> jsonlite 2.0.0 2025-03-27 [1] CRAN (R 4.6.2)
#> knitr 1.52 2026-09-06 [1] CRAN (R 4.6.2)
#> labeling 0.4.3 2023-08-29 [1] CRAN (R 4.6.2)
#> lattice 0.23-1 2026-08-12 [3] CRAN (R 4.6.2)
#> lifecycle 1.0.5 2026-01-08 [1] CRAN (R 4.6.2)
#> magrittr 2.0.5 2026-04-04 [1] CRAN (R 4.6.2)
#> MASS 7.3-66 2026-07-15 [3] CRAN (R 4.6.2)
#> otel 0.3.0 2026-11-07 [1] CRAN (R 4.6.2)
#> pillar 1.11.1 2025-09-17 [1] CRAN (R 4.6.2)
#> pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 4.6.2)
#> purrr 1.2.2 2026-04-10 [1] CRAN (R 4.6.2)
#> R6 2.6.1 2025-02-15 [1] CRAN (R 4.6.2)
#> RColorBrewer 1.1-3 2022-04-03 [1] CRAN (R 4.6.2)
#> Rcpp 1.1.2 2026-07-05 [1] CRAN (R 4.6.2)
#> rjags 5-5 2026-11-21 [1] CRAN (R 4.6.2)
#> rlang 1.3.0 2026-07-05 [1] CRAN (R 4.6.2)
#> rmarkdown 2.32 2026-09-01 [1] CRAN (R 4.6.2)
#> rngtools 1.5.2 2021-09-20 [1] CRAN (R 4.6.2)
#> runjags * 2.3.1-1 2026-11-23 [1] CRAN (R 4.6.2)
#> S7 1.0.0 2026-11-19 [1] CRAN (R 4.6.2)
#> scales 1.4.0 2025-04-24 [1] CRAN (R 4.6.2)
#> serocalculator 1.4.1 2026-03-25 [1] CRAN (R 4.6.2)
#> serodynamics * 0.1.0.9025 2026-11-25 [1] local
#> sessioninfo 1.2.4 2026-06-04 [1] CRAN (R 4.6.2)
#> tibble 3.3.1 2026-01-11 [1] CRAN (R 4.6.2)
#> tidyr 1.3.2 2025-12-19 [1] CRAN (R 4.6.2)
#> tidyselect 1.2.1 2024-03-11 [1] CRAN (R 4.6.2)
#> utf8 1.2.6 2025-06-08 [1] CRAN (R 4.6.2)
#> vctrs 0.7.3 2026-04-11 [1] CRAN (R 4.6.2)
#> withr 3.0.3 2026-06-19 [1] CRAN (R 4.6.2)
#> xfun 0.62 2026-10-16 [1] CRAN (R 4.6.2)
#> yaml 2.3.12 2025-12-10 [1] CRAN (R 4.6.2)
#>
#> [1] /home/runner/work/_temp/Library
#> [2] /opt/R/4.6.2/lib/R/site-library
#> [3] /opt/R/4.6.2/lib/R/library
#> * ── Packages attached to the search path.
#>
#> ──────────────────────────────────────────────────────────────────────────────