run_serodynamics() takes a data frame and adjustable MCMC inputs to
runjags::run.jags() as an MCMC
Bayesian model to estimate antibody dynamic curve parameters.
The rjags::jags.model() models seroresponse dynamics to an
infection. Priors are required for modeling and must be specified prior to
running run_serodynamics. The antibody dynamic curve includes the
following parameters:
y0 = baseline antibody concentration
y1 = peak antibody concentration
t1 = time to peak
shape = shape parameter, estimated for power decay and fixed at 1 for exponential decay
alpha = decay rate
Usage
run_serodynamics(
data,
file_mod = NULL,
decay_type = "power",
nchain = 4,
nadapt = 0,
nburn = 0,
nmc = 100,
niter = 100,
strat = NA,
with_post = FALSE,
with_pop_params = FALSE,
preclogy_per_iso = FALSE,
...
)Arguments
- data
A
base::data.frame()with the following columns.- file_mod
The model file path. If
NULL, a built-in model file is selected based ondecay_type. If supplied, its parameterization must be compatible withdecay_type.- decay_type
A character string specifying the decay function used in the model. Options are
"power"and"exponential". Default is"power". The"power"option usesy(t) = (y1^(1-shape) - (1-shape)*alpha*(t-t1))^(1/(1-shape)). The"exponential"option usesy(t) = y1 * exp(-alpha*(t-t1)). The exponential model does not estimateshape; its processed output includesshape = 1as a fixed value to preserve the common output structure. Note:prep_priors()validates 5-element prior vector for power decay and 4-element prior vectors for exponential decay (the fifth (shape) prior is excluded in exponential decay).- nchain
An integer between 1 and 4 that specifies the number of MCMC chains to be run per jags model.
- nadapt
An integer specifying the number of adaptations per chain.
- nburn
An integer specifying the number of burn ins before sampling.
- nmc
An integer specifying the number of samples in posterior chains.
- niter
An integer specifying the number of iterations.
- strat
A character string specifying the stratification variable, entered in quotes.
- with_post
A logical value specifying whether a raw
jags.postobject should be included as an optional"jags.post"attribute on the returnedsr_modeltibble (seeValuesection below for details). Note: These objects can be large.- with_pop_params
A logical value specifying whether population level parameters should be included as an attribute entitled
population_params. Excluded by default. Note: These objects can be large.- preclogy_per_iso
A logical value. When
TRUEandwith_pop_paramsis alsoTRUE, theParametercolumn forprec.logyrows inpopulation_paramswill contain the antigen/isotype label (e.g.,"HlyE_IgA") rather than the constant"prec.logy". This allows grouping byParameterto obtain per-isotype precision estimates directly. Default isFALSE(allprec.logyrows shareParameter = "prec.logy"; theIso_typecolumn distinguishes isotypes).- ...
Arguments passed on to
prep_priorsmax_antigensAn integer specifying how many antigen-isotypes (biomarkers) will be modeled.
mu_hyp_paramA numeric vector of 5 values representing the prior mean for the population level parameters parameters (y0, y1, t1, alpha, r) for each biomarker. Will be 5 values long specified by the user, representing the following parameters:
y0 = baseline antibody concentration
y1 = peak antibody concentration
t1 = time to peak
alpha = decay rate
r = shape parameter (If running
decay_type == "exponential"no shape parameter needs to be specified). Whendecay_type = "exponential"only 4 parameters (y0, y1, t1, alpha) are used.
prec_hyp_paramA numeric vector of 5 values corresponding to hyperprior diagonal entries for the precision matrix (i.e. inverse variance) representing prior covariance of uncertainty around
mu_hyp_param. Will be 5 values long corresponding to the 5 estimated parameters (4 values whendecay_type = "exponential").omega_paramA numeric vector of 5 values corresponding to the diagonal entries representing the Wishart hyperprior distributions of
prec_hyp_param, describing how much we expect parameters to vary between individuals. Will be 5 values long corresponding to the 5 estimated parameters (4 values whendecay_type = "exponential").wishdf_paramAn integer vector of 1 value specifying the degrees of freedom for the Wishart hyperprior distribution of
prec_hyp_param. Must be 1 value long.The value of
wishdf_paramcontrols how informative the Wishart prior is. Higher values lead to tighter priors on individual variation. Lower values (e.g., 5–10) make the prior more weakly informative, which can help improve convergence if the model is over-regularized.
prec_logy_hyp_paramA numeric vector of 2 values corresponding to hyperprior diagonal entries on the log-scale for the precision matrix (i.e. inverse variance) representing prior beliefs of individual variation. Must be 2 values long.
Value
An sr_model class object: a subclass of tibble::tbl_df that
contains MCMC samples from the joint posterior distribution of the model
parameters, conditional on the provided input data,
including the following:
Iteration= Number of sampling iterationsChain= Number of MCMC chains run; between 1 and 4Parameter= Parameter being estimated. Includes the following:y0= Posterior estimate of baseline antibody concentrationy1= Posterior estimate of peak antibody concentrationt1= Posterior estimate of time to peakalpha= Posterior estimate of decay rateshape= shape parameter, estimated for power decay and fixed at 1 for exponential decay
Iso_type= Antibody/antigen type combination being evaluatedStratification= The variable used to stratify jags modelSubject= ID of subject being evaluatedvalue= Estimated value of the parameterThe following attributes are included in the output:
class: Class of the output object.nChains: Number of chains run.nParameters: The amount of parameters estimated in the model.nIterations: Number of iteration specified.nBurnin: Number of burn ins.nThin: Thinning number (niter/nmc).population_params: Optionally included modeled population parameters, returned as a data.frame and excluded by default. Columns includeIteration,Chain,Parameter,Iso_type,Stratification,Population_Parameter, andvalue.Population_Parameteridentifies which modeled population parameter is represented:mu.par= The population means of the host-specific model parameters (on logarithmic scales). Note: y1 and shape are transformed; shape is not included for exponential decay.prec.par= The population precision matrix of the hyperparameters (with diagonal elements equal to inverse variances). The two parameters listed (separated by commas) represent the pairwise precision relationship between specified parameters.prec.logy= A vector of population precisions (inverse variances), one per antigen/isotype combination.
priors: A list that summarizes the input priors, including:mu_hyp_paramprec_hyp_paramomega_paramwishdfprec_logy_hyp_param
original_data: The original inputdata, stored so that fitted and residual values can be computed on demand (e.g. byplot_residuals()) viacalc_fit_mod(). The attachment offitted_residualsas an attribute was removed in version 0.1.0.9017.strat: The stratification variable name (or NA when no stratification was used), stored alongsideoriginal_datafor the same purpose.decay_type: The decay function used ("power"or"exponential").An optional
"jags.post"attribute, included when argumentwith_post= TRUE.
Examples
if (!is.element(runjags::findjags(), c("", NULL))) {
library(runjags)
set.seed(1)
library(dplyr)
strat1 <- serocalculator::typhoid_curves_nostrat_100 |>
sim_case_data(n = 100) |>
mutate(strat = "stratum 2")
strat2 <- serocalculator::typhoid_curves_nostrat_100 |>
sim_case_data(n = 100) |>
mutate(strat = "stratum 1")
dataset <- bind_rows(strat1, strat2)
fitted_model <- run_serodynamics(
data = dataset, # The data set input
file_mod = serodynamics_example("model.jags"),
nchain = 4, # Number of mcmc chains to run
nadapt = 100, # Number of adaptations to run
nburn = 100, # Number of unrecorded samples before sampling begins
nmc = 1000,
niter = 2000, # Number of iterations
strat = "strat", # Variable to be stratified
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)
)
}
#>
#> Attaching package: ‘dplyr’
#> The following objects are masked from ‘package:stats’:
#>
#> filter, lag
#> The following objects are masked from ‘package:base’:
#>
#> intersect, setdiff, setequal, union
#> 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:00:53 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: 3020
#> Unobserved stochastic nodes: 535
#> Total graph size: 44517
#> . Reading parameter file inits1.txt
#> . Initializing model
#> . Adaptation skipped: model is not in adaptive mode.
#> . Updating 100
#> -------------------------------------------------| 100
#> ************************************************** 100%
#> . . . . . . Updating 2000
#> -------------------------------------------------| 2000
#> ************************************************** 100%
#> . . . . 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 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:02:07 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: 2555
#> Unobserved stochastic nodes: 535
#> Total graph size: 39309
#> . Reading parameter file inits1.txt
#> . Initializing model
#> . Adaptation skipped: model is not in adaptive mode.
#> . Updating 100
#> -------------------------------------------------| 100
#> ************************************************** 100%
#> . . . . . . Updating 2000
#> -------------------------------------------------| 2000
#> ************************************************** 100%
#> . . . . 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