| Title: | Bayesian Dynamic Energy Budget Modelling |
|---|---|
| Description: | Provides a Bayesian framework for Dynamic Energy Budget (DEB) modelling via 'Stan'. Implements the standard DEB model of Kooijman (2010, <doi:10.1017/CBO9780511805400>) as a state-space model with Hamiltonian Monte Carlo inference (Carpenter et al., 2017, <doi:10.18637/jss.v076.i01>). Includes individual-level growth models, growth-reproduction models, hierarchical multi-individual models with partial pooling, and toxicokinetic-toxicodynamic (TKTD) models for ecotoxicology following the DEBtox framework (Jager et al., 2006, <doi:10.1007/s10646-006-0060-x>). Supports prior specification from biological knowledge, convergence diagnostics (Vehtari et al., 2021, <doi:10.1214/20-BA1221>), posterior predictive checks, derived quantity estimation, and visualisation via 'ggplot2'. |
| Authors: | Branimir K. Hackenberger [aut, cre], Tamara Djerdj [aut], Domagoj K. Hackenberger [aut] |
| Maintainer: | Branimir K. Hackenberger <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.0 |
| Built: | 2026-05-12 14:16:17 UTC |
| Source: | https://github.com/sciom/BayesianDEB |
Computes the temperature correction factor for DEB rate parameters
based on the Arrhenius relationship (Kooijman, 2010, Eq. 1.2). In
DEB theory all rate parameters (e.g., , ,
) scale with temperature by the same factor:
arrhenius(temp, T_ref = 293.15, T_A = 8000)arrhenius(temp, T_ref = 293.15, T_A = 8000)
temp |
Body (or ambient) temperature in Kelvin. Renamed from
|
T_ref |
Reference temperature in Kelvin (default 293.15 K = 20 °C). |
T_A |
Arrhenius temperature in Kelvin (default 8000 K). |
where and are in Kelvin and
is the Arrhenius temperature (a species-specific constant, typically
6000–12000 K for ectotherms; Kooijman, 2010, Table 8.1). At
, the factor is exactly 1.
Numeric correction factor (dimensionless, > 0).
Kooijman, S.A.L.M. (2010). Dynamic Energy Budget Theory for Metabolic Organisation. 3rd edition. Cambridge University Press, Eq. 1.2. doi:10.1017/CBO9780511805400
# Correction at 25 C relative to 20 C reference arrhenius(298.15, T_ref = 293.15, T_A = 8000) # ~ 1.74 # No correction at reference temperature arrhenius(293.15) # exactly 1# Correction at 25 C relative to 20 C reference arrhenius(298.15, T_ref = 293.15, T_A = 8000) # ~ 1.74 # No correction at reference temperature arrhenius(293.15) # exactly 1
Converts long-format data frames into the structured list required by
the BayesianDEB Stan programs. Growth observations are matched to the
DEB state variable (structural length); reproduction
records are interval counts of offspring over . The function validates column names, rejects
negative times/lengths, sorts by individual and time, and (for
hierarchical models) pads ragged observation vectors into matrices with
NaN fill, as required by Stan's fixed-size array declarations.
bdeb_data(growth = NULL, reproduction = NULL, concentration = NULL, f_food = 1)bdeb_data(growth = NULL, reproduction = NULL, concentration = NULL, f_food = 1)
growth |
A data frame with columns: |
reproduction |
A data frame with columns: |
concentration |
Optional named numeric vector or data frame mapping
individual/group id to external toxicant concentration |
f_food |
Scaled functional response |
A bdeb_data object (S3 list) ready for bdeb_model().
Kooijman, S.A.L.M. (2010). Dynamic Energy Budget Theory for Metabolic Organisation. 3rd edition. Cambridge University Press. doi:10.1017/CBO9780511805400
# Simple growth data df <- data.frame( id = rep(1, 10), time = seq(0, 45, by = 5), length = c(0.1, 0.15, 0.22, 0.30, 0.38, 0.44, 0.49, 0.52, 0.54, 0.55) ) dat <- bdeb_data(growth = df)# Simple growth data df <- data.frame( id = rep(1, 10), time = seq(0, 45, by = 5), length = c(0.1, 0.15, 0.22, 0.30, 0.38, 0.44, 0.49, 0.52, 0.54, 0.55) ) dat <- bdeb_data(growth = df)
Transforms the raw DEB parameter draws into biologically interpretable quantities, automatically propagating parameter uncertainty. All formulas follow Kooijman (2010, Ch. 3, Table 3.1) strictly.
bdeb_derived(object, ...) ## Default S3 method: bdeb_derived(object, ...) ## S3 method for class 'bdeb_fit' bdeb_derived(object, quantities = c("L_inf", "k_M", "growth_rate"), f = 1, ...)bdeb_derived(object, ...) ## Default S3 method: bdeb_derived(object, ...) ## S3 method for class 'bdeb_fit' bdeb_derived(object, quantities = c("L_inf", "k_M", "growth_rate"), f = 1, ...)
object |
A |
... |
Additional arguments passed to methods. |
quantities |
Character vector of quantities to compute. One or
more of |
f |
Scaled functional response |
A posterior::draws_df with one column per requested quantity and one row per posterior draw.
DEB theory distinguishes several length measures. This function
returns structural length , which is the cube
root of structural volume. Structural length is not the same as
physical (observed) length , which relates to
via the shape coefficient: . The shape
coefficient is species-specific (typically 0.1–0.5)
and is not estimated by this package. If your data are physical
lengths, you should either (a) convert to structural length before
fitting, or (b) divide L_inf by your species' to
obtain the physical asymptotic length.
"L_m"Maximum structural length at
(Kooijman, 2010, Table 3.1):
This is a species-level constant independent of food. Units: cm.
"L_inf"Ultimate structural length at food level
(Kooijman, 2010, Eq. 3.4):
The asymptotic length when at constant food.
Depends on .
Units: cm. Dimensional check:
.
"k_M"Somatic maintenance rate constant:
Units: d.
"growth_rate"Von Bertalanffy growth rate (Kooijman, 2010, Eq. 3.23):
where is the energy
investment ratio. Depends on . Units: d.
"g"Energy investment ratio (Kooijman, 2010, Table 3.1):
Dimensionless. Large means growth is expensive relative
to reserve turnover.
For Eisenia fetida with AmP parameters ,
, :
cm (structural).
With , the physical maximum length would
be mm, consistent with observations.
Kooijman, S.A.L.M. (2010). Dynamic Energy Budget Theory for Metabolic Organisation. 3rd edition. Cambridge University Press. doi:10.1017/CBO9780511805400
Marques, G.M., Augustine, S., Lika, K., Pecquerie, L., Domingos, T. and Kooijman, S.A.L.M. (2018). The AmP project: comparing species on the basis of dynamic energy budget parameters. PLOS Computational Biology, 14(5), e1006100. doi:10.1371/journal.pcbi.1006100
## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) bdeb_derived(fit, quantities = c("L_inf", "k_M")) ## End(Not run)## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) bdeb_derived(fit, quantities = c("L_inf", "k_M")) ## End(Not run)
Reports a comprehensive set of NUTS/HMC diagnostics following the recommendations of Vehtari et al. (2021):
Indicate that the numerical leapfrog
integrator encountered regions of high curvature. Even a single
divergence can bias the posterior. Remedy: increase adapt_delta.
The NUTS trajectory hit the maximum
allowed tree depth, meaning it could not find a U-turn. Remedy:
increase max_treedepth.
Energy Bayesian Fraction of Missing Information. Values below 0.3 indicate that the momentum resampling is inefficient (Betancourt, 2016).
Split- convergence diagnostic.
Values > 1.01 indicate incomplete mixing across chains.
Effective sample size for the bulk and tails of the posterior. Values below 400 suggest that posterior summaries may be unreliable.
bdeb_diagnose(fit, pars = NULL)bdeb_diagnose(fit, pars = NULL)
fit |
A |
pars |
Character vector of parameter names to report. Default:
all model parameters (excluding generated quantities such as
|
Returns a bdeb_diagnostics S3 object. The object has dedicated
print(),
summary() and
plot() methods. When called interactively
the print method is invoked automatically; assign the result
(d <- bdeb_diagnose(fit)) to suppress output.
An object of class bdeb_diagnostics with components
n_divergent, n_max_treedepth, ebfmi, summary (a
posterior::summarise_draws() tibble), pars, and model_type.
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and
Bürkner, P.-C. (2021). Rank-normalization, folding, and localization:
an improved for assessing convergence of MCMC.
Bayesian Analysis, 16(2), 667–718. doi:10.1214/20-BA1221
Betancourt, M. (2016). Diagnosing biased inference with divergences. Stan case study. https://mc-stan.org/users/documentation/case-studies/divergences_and_bias.html
print.bdeb_diagnostics(), summary.bdeb_diagnostics(),
plot.bdeb_diagnostics()
## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual"), chains = 2, iter_warmup = 200, iter_sampling = 200) d <- bdeb_diagnose(fit) summary(d) plot(d, type = "rhat") ## End(Not run)## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual"), chains = 2, iter_warmup = 200, iter_sampling = 200) d <- bdeb_diagnose(fit) summary(d) plot(d, type = "rhat") ## End(Not run)
Extracts the full posterior distribution of the
and the NEC (no-effect concentration, ) from a fitted DEBtox
model. Both quantities are computed analytically in the Stan
generated quantities block, avoiding the need for post-hoc root
finding. At toxicokinetic steady state the stress factor equals
for , so setting
yields
bdeb_ec50(fit, prob = 0.9, verbose = TRUE)bdeb_ec50(fit, prob = 0.9, verbose = TRUE)
fit |
A |
prob |
Credible interval probability. Default 0.90. |
verbose |
Logical; if |
The NEC is the threshold concentration below which no effect occurs;
it corresponds directly to the parameter in the damage
model of Kooijman & Bedaux (1996).
A named list with:
draws: posterior draws of EC50
summary: mean, median, sd, lower, upper
NEC: posterior summary of the no-effect concentration
Kooijman, S.A.L.M. and Bedaux, J.J.M. (1996). The Analysis of Aquatic Toxicity Data. VU University Press, Amsterdam.
## Not run: data(debtox_growth) dat <- bdeb_data(growth = debtox_growth, concentration = c("1" = 0, "11" = 20, "21" = 80, "31" = 200)) fit <- bdeb_fit(bdeb_tox(dat, stress = "assimilation")) bdeb_ec50(fit, prob = 0.95) ## End(Not run)## Not run: data(debtox_growth) dat <- bdeb_data(growth = debtox_growth, concentration = c("1" = 0, "11" = 20, "21" = 80, "31" = 200)) fit <- bdeb_fit(bdeb_tox(dat, stress = "assimilation")) bdeb_ec50(fit, prob = 0.95) ## End(Not run)
Compiles the bundled Stan program via cmdstanr (which handles
caching internally based on the Stan source hash) and runs the
No-U-Turn Sampler (NUTS; Hoffman & Gelman, 2014). The Stan ODE system is solved at each leapfrog step
using the BDF stiff solver (ode_bdf) with absolute and relative
tolerances of .
bdeb_fit( model, chains = 4, iter_warmup = 1000, iter_sampling = 1000, adapt_delta = 0.8, max_treedepth = 10, seed = NULL, parallel_chains = NULL, threads_per_chain = NULL, refresh = 200, algorithm = c("sampling", "variational"), ... )bdeb_fit( model, chains = 4, iter_warmup = 1000, iter_sampling = 1000, adapt_delta = 0.8, max_treedepth = 10, seed = NULL, parallel_chains = NULL, threads_per_chain = NULL, refresh = 200, algorithm = c("sampling", "variational"), ... )
model |
A |
chains |
Number of independent MCMC chains. Default 4 (the minimum
recommended by Vehtari et al., 2021, for reliable |
iter_warmup |
Number of warmup (adaptation) iterations per chain. Default 1000. Stan uses dual-averaging to tune the step size and diagonal mass matrix during warmup. |
iter_sampling |
Number of post-warmup sampling iterations per chain. Default 1000 (yielding 4000 total draws with 4 chains). |
adapt_delta |
Target Metropolis acceptance probability for NUTS. Default 0.8. Increase toward 1.0 to reduce divergences at the cost of smaller step sizes and longer runtime. |
max_treedepth |
Maximum binary-tree depth for NUTS. Default 10
(i.e., up to |
seed |
Integer random seed for full reproducibility. |
parallel_chains |
Number of chains to run in parallel.
Default |
threads_per_chain |
Number of threads per chain for within-chain
parallelism via Stan's |
refresh |
How often to print sampling progress (iterations). Default 200. Set to 0 for silent operation. |
algorithm |
One of |
... |
Additional arguments forwarded to |
Tuning guidance. If bdeb_diagnose() reports divergent transitions,
increase adapt_delta toward 1.0 (e.g., 0.95 or 0.99). This reduces
the step size, trading speed for geometric fidelity of the sampler. If
the maximum treedepth is frequently saturated, increase
max_treedepth (e.g., 12 or 15). For hierarchical models, starting
values can matter; the non-centred parameterisation used in
bdeb_hierarchical_growth.stan should suffice in most cases.
A bdeb_fit object containing the CmdStanMCMC (or
CmdStanVB) result, the model specification, and sampling
metadata. The list element algorithm records which inference
engine was used.
During warmup it is normal for Stan to emit informational messages
such as "Informational Message: The current Metropolis proposal is
about to be rejected because of the following issue(s)" or
occasional ODE solver warnings. These are emitted whenever the
leapfrog integrator probes a region of parameter space where the
DEB ODE is stiff or numerically extreme; the proposal is then
rejected and the chain continues. As of version 0.2.0 the bundled
Stan models call ode_bdf_tol with max_num_steps = 1e5
(raised from 1e4 in 0.1.x) which substantially reduces these
messages but does not eliminate them in pathological priors or with
very few warmup iterations. These messages are benign as long
as bdeb_diagnose() reports no divergent transitions, no max
treedepth saturation, and adequate /ESS for all
parameters.
Hoffman, M.D. and Gelman, A. (2014). The No-U-Turn Sampler: adaptively setting path lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47), 1593–1623.
Vehtari, A., Gelman, A., Simpson, D., Carpenter, B. and
Bürkner, P.-C. (2021). Rank-normalization, folding, and localization:
an improved for assessing convergence of MCMC.
Bayesian Analysis, 16(2), 667–718. doi:10.1214/20-BA1221
# bdeb_fit() requires the external CmdStan toolchain (Suggests: # cmdstanr) and a fresh fit takes > 30 seconds (Stan compilation # plus MCMC). The example is wrapped in \donttest{} and gated on # cmdstanr availability so that R CMD check skips it on CRAN's # toolchain-free workers but power users can run it after # cmdstanr::install_cmdstan(). if (requireNamespace("cmdstanr", quietly = TRUE) && nzchar(tryCatch(cmdstanr::cmdstan_path(), error = function(e) ""))) { data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) mod <- bdeb_model(dat, type = "individual") fit <- bdeb_fit(mod, chains = 1, iter_warmup = 200, iter_sampling = 200, refresh = 0) print(fit) }# bdeb_fit() requires the external CmdStan toolchain (Suggests: # cmdstanr) and a fresh fit takes > 30 seconds (Stan compilation # plus MCMC). The example is wrapped in \donttest{} and gated on # cmdstanr availability so that R CMD check skips it on CRAN's # toolchain-free workers but power users can run it after # cmdstanr::install_cmdstan(). if (requireNamespace("cmdstanr", quietly = TRUE) && nzchar(tryCatch(cmdstanr::cmdstan_path(), error = function(e) ""))) { data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) mod <- bdeb_model(dat, type = "individual") fit <- bdeb_fit(mod, chains = 1, iter_warmup = 200, iter_sampling = 200, refresh = 0) print(fit) }
Computes approximate leave-one-out cross-validation (LOO-CV) using
Pareto-smoothed importance sampling (PSIS; Vehtari et al., 2017).
Requires that the Stan model includes a log_lik array in the
generated quantities block.
bdeb_loo(fit, endpoint = c("all", "growth", "reproduction"), ...)bdeb_loo(fit, endpoint = c("all", "growth", "reproduction"), ...)
fit |
A |
endpoint |
Which log-likelihood to use for |
... |
Additional arguments passed to |
Currently supported for "individual" and "growth_repro" models
only. The "hierarchical" and "debtox" models do not store
per-observation log_lik in generated quantities:
"hierarchical" computes the likelihood inside reduce_sum
(no access to individual contributions outside the function);
"debtox" uses the same reduce_sum approach and its
generated quantities block only computes EC50/NEC.
Adding per-group log_lik to DEBtox is planned for a future
version. An informative error is raised for unsupported types.
A loo object (see loo::loo()).
For "growth_repro" models with endpoint = "all", growth and
reproduction observations are concatenated and each treated as an
independent data point. This is valid because the two endpoints are
conditionally independent given the latent DEB process (growth
observations depend only on , reproduction counts depend
only on ; given the ODE solution, they share no
additional error). Use endpoint = "growth" or
endpoint = "reproduction" to compute LOO for a single endpoint.
Vehtari, A., Gelman, A. and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27(5), 1413–1432. doi:10.1007/s11222-016-9696-4
## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) bdeb_loo(fit) ## End(Not run)## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) bdeb_loo(fit) ## End(Not run)
Creates a model specification that binds together the prepared data, the
DEB process model (encoded as a pre-written Stan program), the prior
distributions, and the observation model. Internally it calls the
appropriate build_stan_data_*() function to assemble the list of
named values that Stan expects. The Stan program is not compiled at
this stage — compilation and sampling happen in bdeb_fit().
bdeb_model( data, type = c("individual", "growth_repro", "hierarchical", "debtox"), priors = list(), observation = list(), temperature = NULL )bdeb_model( data, type = c("individual", "growth_repro", "hierarchical", "debtox"), priors = list(), observation = list(), temperature = NULL )
data |
A |
type |
Model type: |
priors |
Named list of |
observation |
Named list of observation model specs for each endpoint.
Default: |
temperature |
Optional list with components |
The four model types correspond to increasingly complex DEB formulations:
"individual"Standard 2-state DEB (reserve , structure
), Kooijman (2010, Ch. 2). The ODE is solved with Stan's
ode_bdf (stiff BDF solver) at tolerances .
"growth_repro"3-state model adding the reproduction buffer
. Offspring counts are modelled as
,
where .
"hierarchical"2-state model with a lognormal random effect on
: ,
(non-centred). Shared parameters
are estimated from all individuals
jointly (partial pooling; Gelman & Hill, 2006). Initial
structural length varies per individual; initial
reserve density is shared (assumes organisms start with
the same reserve state, which is typical for lab-reared cohorts).
"debtox"4-state TKTD model following Jager et al. (2006).
Adds scaled damage with
.
The is computed analytically as
.
A bdeb_model object (S3 list).
Kooijman, S.A.L.M. (2010). Dynamic Energy Budget Theory for Metabolic Organisation. 3rd edition. Cambridge University Press. doi:10.1017/CBO9780511805400
Gelman, A. and Hill, J. (2006). Data Analysis Using Regression and Multilevel/Hierarchical Models. Cambridge University Press.
Jager, T., Heugens, E.H.W. and Kooijman, S.A.L.M. (2006). Making sense of ecotoxicological test results: towards application of process-based models. Ecotoxicology, 15(3), 305–314. doi:10.1007/s10646-006-0060-x
df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) mod <- bdeb_model(dat, type = "individual") print(mod) summary(mod)df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) mod <- bdeb_model(dat, type = "individual") print(mod) summary(mod)
Visualisation methods for BDEB fits, posterior predictive checks, and derived quantities using ggplot2. All plots return ggplot2 objects that can be further customised.
Extracts replicated data generated in the Stan
generated quantities block and pairs them with the observed data
. Following Gelman et al. (2013, Ch. 6), posterior predictive
checks (PPCs) answer: "could the observed data plausibly have been
generated by the fitted model?" If the replicated data envelopes
consistently miss systematic features of , the model is
mis-specified.
bdeb_ppc(fit, type = c("growth", "reproduction", "all"))bdeb_ppc(fit, type = c("growth", "reproduction", "all"))
fit |
A |
type |
Which endpoint to check: |
For growth endpoints, the replicated lengths
are drawn as in
the Stan program. For reproduction, .
A bdeb_ppc object containing observed data (L_obs or
R_obs), a matrix of replicated data (L_rep or R_rep), and
metadata for plot.bdeb_ppc().
"individual"Full PPC with L_rep and L_obs.
"growth_repro"Growth PPC via L_rep; reproduction PPC
via R_rep.
"hierarchical"Not available. The Stan model uses
reduce_sum and does not generate L_rep. Use
bdeb_diagnose() and trace plots for model checking.
"debtox"Not available for the same reason. Use
plot_dose_response() for visual model checking.
Gelman, A., Carlin, J.B., Stern, H.S., Dunson, D.B., Vehtari, A. and Rubin, D.B. (2013). Bayesian Data Analysis. 3rd edition. Chapman & Hall/CRC. (Chapter 6: Model checking.)
## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) ppc <- bdeb_ppc(fit, type = "growth") plot(ppc) ## End(Not run)## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) ppc <- bdeb_ppc(fit, type = "growth") plot(ppc) ## End(Not run)
Simulates growth trajectories by sampling parameters from the prior
distributions and forward-integrating the DEB ODE in R (Euler method).
This is the prior analogue of bdeb_ppc() and answers: "what range
of data does the model predict before seeing any data?" Following
Gabry et al. (2019), if the prior predictive distribution covers
biologically implausible values, the priors should be tightened.
bdeb_prior_predictive(model, n_draws = 500, dt = 0.5, seed = NULL)bdeb_prior_predictive(model, n_draws = 500, dt = 0.5, seed = NULL)
model |
A |
n_draws |
Number of prior draws. Default 500. |
dt |
Euler step size (days). Default 0.5. |
seed |
Integer seed for reproducibility. Default |
Does not require CmdStan — all sampling and simulation is done
in R using Euler integration (step size dt). This is an
approximate visualisation tool, not exact Stan inference. The
ODE trajectories may differ slightly from the BDF solver used during
fitting.
A list with class "bdeb_prior_predictive" containing:
tTime vector.
LMatrix of simulated trajectories (draws x time points).
L_infVector of prior-predictive ultimate lengths.
priorsNamed list of prior objects used.
Gabry, J., Simpson, D., Vehtari, A., Betancourt, M. and Gelman, A. (2019). Visualization in Bayesian workflow. Journal of the Royal Statistical Society: Series A, 182(2), 389–402. doi:10.1111/rssa.12378
dat <- bdeb_data(growth = data.frame(id = 1, time = 0:10, length = seq(0.1, 0.5, length.out = 11))) mod <- bdeb_model(dat, type = "individual") pp <- bdeb_prior_predictive(mod, n_draws = 100, seed = 1) plot(pp, n_draws = 30)dat <- bdeb_data(growth = data.frame(id = 1, time = 0:10, length = seq(0.1, 0.5, length.out = 11))) mod <- bdeb_model(dat, type = "individual") pp <- bdeb_prior_predictive(mod, n_draws = 100, seed = 1) plot(pp, n_draws = 30)
bdeb_prior ObjectsDisplay, summarise, and plot a bdeb_prior object returned by
prior_lognormal(), prior_normal(), prior_beta(),
prior_halfnormal(), prior_halfcauchy(), or
prior_exponential().
## S3 method for class 'bdeb_prior' print(x, ...) ## S3 method for class 'bdeb_prior' summary(object, ...) ## S3 method for class 'summary.bdeb_prior' print(x, ...) ## S3 method for class 'bdeb_prior' plot(x, n = 200, ...)## S3 method for class 'bdeb_prior' print(x, ...) ## S3 method for class 'bdeb_prior' summary(object, ...) ## S3 method for class 'summary.bdeb_prior' print(x, ...) ## S3 method for class 'bdeb_prior' plot(x, n = 200, ...)
x, object
|
A |
... |
Ignored. |
n |
Number of grid points for the density curve. Default 200. |
print() returns the object invisibly. summary() returns
a list with theoretical mean, sd, and the 5th, 50th, and 95th
quantiles where defined for the family. plot() returns a
ggplot2::ggplot object showing the prior density between the
0.001 and 0.999 quantiles.
p <- prior_lognormal(mu = 1.5, sigma = 0.5) print(p) summary(p) plot(p)p <- prior_lognormal(mu = 1.5, sigma = 0.5) print(p) summary(p) plot(p)
Prints a concise summary of the software environment used for a BayesianDEB analysis. Useful for supplementary materials in publications or for diagnosing cross-machine discrepancies.
bdeb_session_info(fit = NULL)bdeb_session_info(fit = NULL)
fit |
Optional |
Invisibly returns a named list with all reported information.
bdeb_session_info()bdeb_session_info()
Convenience wrapper for bdeb_model() that sets type = "debtox" and
provides a stress argument to select the physiological mode of action
(PMoA) of the toxicant. The underlying TKTD framework follows
Jager et al. (2006) and the GUTS-RED-SD simplification of
Jager & Zimmer (2012):
bdeb_tox( data, stress = c("assimilation", "maintenance", "growth_cost"), priors = list(), ... )bdeb_tox( data, stress = c("assimilation", "maintenance", "growth_cost"), priors = list(), ... )
data |
A |
stress |
Physiological mode of action. Currently only
|
priors |
Named list of priors. Missing entries filled from
|
... |
Additional arguments passed to |
Toxicokinetics. Scaled internal damage tracks the
external concentration with first-order kinetics:
where is the dominant rate constant, is the NEC
(no-effect concentration), and is the external concentration.
Stress on assimilation. The assimilation flux is reduced by a
factor , where is the effect
intensity. At steady state (), the
for 50\
.
A bdeb_model object of type "debtox".
Lifecycle: beta. Stress on assimilation is implemented and
tested; "maintenance" and "growth_cost" modes are planned.
Important limitation: the DEBtox model fits one ODE per concentration group, not per individual. If your data contain multiple individuals per concentration, they are automatically aggregated to group means per time point (with a warning). This is appropriate for group-level summary data but does not capture within-group individual variation. A hierarchical DEBtox extension is planned for a future version.
Jager, T., Heugens, E.H.W. and Kooijman, S.A.L.M. (2006). Making sense of ecotoxicological test results: towards application of process-based models. Ecotoxicology, 15(3), 305–314. doi:10.1007/s10646-006-0060-x
Jager, T. and Zimmer, E.I. (2012). Simplified Dynamic Energy Budget model for analysing ecotoxicity data. Ecological Modelling, 225, 74–81. doi:10.1016/j.ecolmodel.2011.11.012
# R-side specification only (no Stan sampling) data(debtox_growth) # one replicate per concentration avoids aggregation warning dt <- debtox_growth[debtox_growth$id %in% c(1, 11, 21, 31), ] dat <- bdeb_data(growth = dt, concentration = c(0, 20, 80, 200)) mod <- bdeb_tox(dat, stress = "assimilation")# R-side specification only (no Stan sampling) data(debtox_growth) # one replicate per concentration avoids aggregation warning dt <- debtox_growth[debtox_growth$id %in% c(1, 11, 21, 31), ] dat <- bdeb_data(growth = dt, concentration = c(0, 20, 80, 200)) mod <- bdeb_tox(dat, stress = "assimilation")
Returns posterior medians of all model parameters as a named numeric
vector, consistent with the S3 coef() convention.
## S3 method for class 'bdeb_fit' coef(object, type = c("median", "mean"), ...)## S3 method for class 'bdeb_fit' coef(object, type = c("median", "mean"), ...)
object |
A |
type |
One of |
... |
Ignored. |
Named numeric vector of point estimates.
## Not run: fit <- bdeb_fit(mod) coef(fit) ## End(Not run)## Not run: fit <- bdeb_fit(mod) coef(fit) ## End(Not run)
Bayesian counterpart to stats::confint(): returns the posterior
central credible interval for each model parameter.
## S3 method for class 'bdeb_fit' confint(object, parm = NULL, level = 0.95, ...)## S3 method for class 'bdeb_fit' confint(object, parm = NULL, level = 0.95, ...)
object |
A |
parm |
Character vector of parameter names. Default: all model parameters. |
level |
Probability mass of the credible interval. Default 0.95. |
... |
Ignored. |
A matrix with one row per parameter and two columns named by
their percentile (e.g. "2.5%", "97.5%" for level = 0.95).
## Not run: fit <- bdeb_fit(mod) confint(fit, level = 0.90) ## End(Not run)## Not run: fit <- bdeb_fit(mod) confint(fit, level = 0.90) ## End(Not run)
Given current state and the core DEB parameters, computes
all standard energy fluxes defined by the -rule
(Kooijman, 2010, Eqs. 2.3–2.12):
deb_fluxes(E, V, f, p_Am, p_M, kappa, v, E_G, k_J = 0, E_Hp = 0)deb_fluxes(E, V, f, p_Am, p_M, kappa, v, E_G, k_J = 0, E_Hp = 0)
E |
Reserve energy (J). |
V |
Structural volume (cm |
f |
Scaled functional response |
p_Am |
Surface-area-specific maximum assimilation rate
|
p_M |
Volume-specific somatic maintenance rate |
kappa |
Allocation fraction to soma |
v |
Energy conductance (cm d |
E_G |
Specific cost of structure |
k_J |
Maturity maintenance rate coefficient |
E_Hp |
Maturity at puberty |
Assimilation: .
Mobilisation: .
Somatic maintenance: .
Growth: .
Maturity maintenance: .
Reproduction: .
Named list with fluxes p_A, p_C, p_M, p_G, p_J,
p_R, structural length L (), and scaled reserve
density e (). The
stabilisation prevents division by zero when ; in that
edge case e returns a small finite number rather than Inf or
NA.
Kooijman, S.A.L.M. (2010). Dynamic Energy Budget Theory for Metabolic Organisation. 3rd edition. Cambridge University Press, Ch. 2. doi:10.1017/CBO9780511805400
# Energy fluxes for a 1 cm^3 organism with typical Eisenia parameters deb_fluxes(E = 1, V = 1, f = 1, p_Am = 5, p_M = 0.5, kappa = 0.75, v = 0.2, E_G = 4400)# Energy fluxes for a 1 cm^3 organism with typical Eisenia parameters deb_fluxes(E = 1, V = 1, f = 1, p_Am = 5, p_M = 0.5, kappa = 0.75, v = 0.2, E_G = 4400)
Forward-integrates the standard 2-state DEB ODE (reserve ,
structure ) using Euler's method. This is a standalone
simulator independent of Stan — useful for exploring parameter
space, generating synthetic data, teaching, and prior predictive
checks.
deb_simulate(t_max, p_Am, p_M, kappa, v, E_G, E0, L0, f = 1, dt = 0.5)deb_simulate(t_max, p_Am, p_M, kappa, v, E_G, E0, L0, f = 1, dt = 0.5)
t_max |
End time (days). |
p_Am |
Surface-area-specific assimilation rate |
p_M |
Volume-specific somatic maintenance |
kappa |
Allocation fraction to soma. |
v |
Energy conductance (cm d |
E_G |
Specific cost of structure (J cm |
E0 |
Initial reserve density (J cm |
L0 |
Initial structural length (cm). |
f |
Scaled functional response |
dt |
Integration step size (days). Default 0.5. |
Data frame with columns time, E (reserve), V (volume),
L (structural length).
This uses the LSODA solver from deSolve, which
automatically switches between stiff (BDF) and non-stiff (Adams)
methods. This matches the BDF solver used in the Stan models,
ensuring numerical consistency between R-side simulation and
Stan-side inference. The dt parameter controls output
resolution, not integration accuracy (governed by rtol/atol
= 1e-6).
# Simulate E. fetida growth for 84 days traj <- deb_simulate(t_max = 84, p_Am = 5, p_M = 0.5, kappa = 0.75, v = 0.2, E_G = 400, E0 = 1, L0 = 0.1) plot(traj$time, traj$L, type = "l", xlab = "Days", ylab = "L (cm)")# Simulate E. fetida growth for 84 days traj <- deb_simulate(t_max = 84, p_Am = 5, p_M = 0.5, kappa = 0.75, v = 0.2, E_G = 400, E0 = 1, L0 = 0.1) plot(traj$time, traj$L, type = "l", xlab = "Days", ylab = "L (cm)")
Simulated growth data under toxicant exposure for 4 concentration
groups (0, 20, 80, 200 arbitrary units) with 10 individuals per group
measured weekly over 6 weeks. Designed for fitting the DEBtox (TKTD)
model in bdeb_tox(). The toxicant acts through stress on
assimilation: the effective assimilation rate is reduced by a factor
following the DEBtox
framework of Jager et al. (2006).
debtox_growthdebtox_growth
A data frame with 280 rows and 4 columns:
Individual identifier (integer, 1–40)
External toxicant concentration (arbitrary units)
Observation time in days (0, 7, 14, ..., 42)
Structural length in cm (with measurement error)
Simulated with NEC , effect intensity
, and base DEB parameters identical to
eisenia_growth.
Jager, T., Heugens, E.H.W. and Kooijman, S.A.L.M. (2006). Making sense of ecotoxicological test results: towards application of process-based models. Ecotoxicology, 15(3), 305–314. doi:10.1007/s10646-006-0060-x
data(debtox_growth) head(debtox_growth)data(debtox_growth) head(debtox_growth)
Forward-integrates the 4-state DEBtox ODE (, ,
, ) with stress on assimilation. Standalone
simulator independent of Stan.
debtox_simulate( t_max, p_Am, p_M, kappa, v, E_G, E0, L0, k_d, z_w, b_w, C_w, f = 1, dt = 0.5 )debtox_simulate( t_max, p_Am, p_M, kappa, v, E_G, E0, L0, k_d, z_w, b_w, C_w, f = 1, dt = 0.5 )
t_max |
End time (days). |
p_Am |
Surface-area-specific assimilation rate |
p_M |
Volume-specific somatic maintenance |
kappa |
Allocation fraction to soma. |
v |
Energy conductance (cm d |
E_G |
Specific cost of structure (J cm |
E0 |
Initial reserve density (J cm |
L0 |
Initial structural length (cm). |
k_d |
Damage recovery rate (d |
z_w |
No-effect concentration (NEC). |
b_w |
Effect intensity. |
C_w |
External toxicant concentration. |
f |
Scaled functional response |
dt |
Integration step size (days). Default 0.5. |
Data frame with columns time, E, V, L, R
(reproduction buffer), Dw (scaled damage).
traj <- debtox_simulate(t_max = 42, p_Am = 5, p_M = 0.5, kappa = 0.75, v = 0.2, E_G = 400, E0 = 1, L0 = 0.1, k_d = 0.3, z_w = 15, b_w = 0.003, C_w = 80) plot(traj$time, traj$L, type = "l")traj <- debtox_simulate(t_max = 42, p_Am = 5, p_M = 0.5, kappa = 0.75, v = 0.2, E_G = 400, E0 = 1, L0 = 0.1, k_d = 0.3, z_w = 15, b_w = 0.003, C_w = 80) plot(traj$time, traj$L, type = "l")
Real experimental growth data for Eisenia andrei exposed to
cadmium in natural soil at 23 °C from Van Gestel et al. (1991),
obtained via the EGrowth database (Mathieu, 2018). Five
concentration groups (0, 10, 32, 100, 320 mg Cd/kg) with 7 time
points each over 85 days. Group-mean body mass was converted to
structural length via with
g cm.
eisenia_cdeisenia_cd
A data frame with 35 rows and 4 columns:
Concentration group identifier (1–5)
Time in days (0–85)
Structural length in cm
Cadmium concentration (mg Cd/kg soil)
EGrowth database, curve IDs gr0119–gr0123. https://github.com/JeromeMathieuEcology/EGrowth
Van Gestel, C.A.M., Van Dis, W.A., Dirven-Van Breemen, E.M., Sparenburg, P.M. and Baerselman, R. (1991). Influence of cadmium, copper, and pentachlorophenol on growth and sexual development of Eisenia andrei (Oligochaeta; Annelida). Biology and Fertility of Soils, 12, 117–121. doi:10.1007/BF00341486
data(eisenia_cd) plot(eisenia_cd$time, eisenia_cd$length, col = as.factor(eisenia_cd$concentration), xlab = "Days", ylab = "Structural length (cm)")data(eisenia_cd) plot(eisenia_cd$time, eisenia_cd$length, col = as.factor(eisenia_cd$concentration), xlab = "Days", ylab = "Structural length (cm)")
Simulated growth dataset for 21 individuals of the earthworm
Eisenia fetida measured weekly over 12 weeks under controlled
laboratory conditions (20 °C, ad libitum feeding), following a
standard OECD 222 test protocol design. DEB parameters are based on
the E. fetida entry in the Add-my-Pet collection (AmP;
Marques et al., 2018). Individual variation in was
drawn from a lognormal distribution with CV 10\
Gaussian measurement error cm was added to
the structural length.
eisenia_growtheisenia_growth
A data frame with 273 rows and 3 columns:
Individual identifier (integer, 1–21)
Observation time in days (0, 7, 14, ..., 84)
Structural length in cm (= ), with
measurement error
Simulated from the standard DEB model (Kooijman, 2010,
Eqs. 2.4–2.6) with parameters:
J/d/cm,
J/d/cm,
,
cm/d,
J/cm.
Individual variation: ,
.
Observation error: cm.
Kooijman, S.A.L.M. (2010). Dynamic Energy Budget Theory for Metabolic Organisation. 3rd edition. Cambridge University Press. doi:10.1017/CBO9780511805400
Marques, G.M., Augustine, S., Lika, K., Pecquerie, L., Domingos, T. and Kooijman, S.A.L.M. (2018). The AmP project: comparing species on the basis of dynamic energy budget parameters. PLOS Computational Biology, 14(5), e1006100. doi:10.1371/journal.pcbi.1006100
OECD (2016). Test No. 222: Earthworm Reproduction Test (Eisenia fetida / Eisenia andrei). OECD Guidelines for the Testing of Chemicals.
data(eisenia_growth) head(eisenia_growth)data(eisenia_growth) head(eisenia_growth)
Real experimental growth data for Eisenia fetida on activated
sludge at 25 °C from Neuhauser, Hartenstein & Kaplan (1980),
obtained via the EGrowth database (Mathieu, 2018). The dataset
comprises 37 group-mean body mass measurements (20 worms per
replicate) over 250 days, from hatchling (~8 mg) to adult
(~2350 mg). Wet mass was converted to structural length via
with tissue density
g cm.
eisenia_neuhausereisenia_neuhauser
A data frame with 37 rows and 3 columns:
Individual/group identifier (always 1)
Time in days since start (1–250)
Structural length in cm (0.20–1.31)
EGrowth database, curve ID gr0226. https://github.com/JeromeMathieuEcology/EGrowth
Neuhauser, E.F., Hartenstein, R. and Kaplan, D.L. (1980). Growth of the earthworm Eisenia foetida in relation to population density and food rationing. Oikos, 35, 93–98. doi:10.2307/3544730
Mathieu, J. (2018). EGrowth: a global database on intraspecific body growth variability in earthworm. Soil Biology and Biochemistry, 122, 71–80. doi:10.1016/j.soilbio.2018.04.004
data(eisenia_neuhauser) plot(eisenia_neuhauser$time, eisenia_neuhauser$length, xlab = "Days", ylab = "Structural length (cm)")data(eisenia_neuhauser) plot(eisenia_neuhauser$time, eisenia_neuhauser$length, xlab = "Days", ylab = "Structural length (cm)")
Posterior point estimate (median or mean) of the latent length
at each observation. Bayesian counterpart of
stats::fitted().
## S3 method for class 'bdeb_fit' fitted(object, type = c("median", "mean"), ...)## S3 method for class 'bdeb_fit' fitted(object, type = c("median", "mean"), ...)
object |
A |
type |
One of |
... |
Ignored. |
Currently supported for "individual" and "growth_repro" models.
For "hierarchical" and "debtox" use bdeb_predict() instead.
Named numeric vector of fitted values, one per observation.
## Not run: fit <- bdeb_fit(mod) fitted(fit) ## End(Not run)## Not run: fit <- bdeb_fit(mod) fitted(fit) ## End(Not run)
Simulated 28-day reproduction dataset for the springtail Folsomia
candida exposed to 5 cadmium concentrations (0, 10, 50, 100,
500 mg Cd/kg dry soil) with 6 replicates per concentration. The
experimental design follows ISO 11267 (springtail reproduction test).
Toxicant effects were simulated using a simple NEC-based model:
expected offspring , with Poisson sampling around the expected value.
folsomia_reprofolsomia_repro
A data frame with 30 rows and 5 columns:
Replicate identifier (integer, 1–30)
Cadmium concentration in mg/kg dry soil
Start of observation interval (day 0)
End of observation interval (day 28)
Number of juveniles produced in the interval
Simulated with NEC mg/kg, effect intensity
(mg/kg), and control offspring
count .
ISO 11267 (2014). Soil quality — Inhibition of reproduction of Collembola (Folsomia candida) by soil contaminants.
data(folsomia_repro) head(folsomia_repro)data(folsomia_repro) head(folsomia_repro)
Computes the log-pointwise predictive density (lppd):
the Bayesian analogue of stats::logLik(). This is the natural
point summary of model fit reported by bdeb_loo() (which adds
Pareto-smoothed importance sampling for cross-validation).
## S3 method for class 'bdeb_fit' logLik(object, ...)## S3 method for class 'bdeb_fit' logLik(object, ...)
object |
A |
... |
Ignored. |
Requires the Stan model to store per-observation log_lik in
generated quantities. Currently available for "individual" and
"growth_repro" models; "hierarchical" and "debtox" compute the
likelihood inside reduce_sum and do not expose individual terms.
A logLik object with attributes df (number of model
parameters) and nobs (number of observations).
## Not run: fit <- bdeb_fit(mod) logLik(fit) ## End(Not run)## Not run: fit <- bdeb_fit(mod) logLik(fit) ## End(Not run)
Returns the total count of growth (and, where relevant, reproduction)
observations that contributed to the likelihood. Matches
stats::nobs() in spirit.
## S3 method for class 'bdeb_fit' nobs(object, ...)## S3 method for class 'bdeb_fit' nobs(object, ...)
object |
A |
... |
Ignored. |
Integer scalar: total number of observations.
## Not run: fit <- bdeb_fit(mod) nobs(fit) ## End(Not run)## Not run: fit <- bdeb_fit(mod) nobs(fit) ## End(Not run)
Observation Model Specifications
obs_normal() obs_lognormal() obs_student_t(nu = 5) obs_poisson() obs_negbinom()obs_normal() obs_lognormal() obs_student_t(nu = 5) obs_poisson() obs_negbinom()
nu |
Degrees of freedom. Default 5. |
A bdeb_obs object (list with class "bdeb_obs").
obs_normal(): Gaussian observation error (default for growth)
obs_lognormal(): Log-normal observation error (multiplicative)
obs_student_t(): Student-t observation error (robust to outliers)
obs_poisson(): Poisson observations (for count data)
obs_negbinom(): Negative binomial observations (overdispersed counts)
obs_normal() obs_lognormal() obs_negbinom()obs_normal() obs_lognormal() obs_negbinom()
Produces a dose-response curve by forward-simulating the full
4-state DEBtox ODE from the posterior in R (Euler integration).
For each posterior draw, the ODE is solved at every concentration in
a fine grid from 0 to . The y-axis shows
the predicted final structural length relative to the control (C = 0)
at the same draw, so that each curve propagates the full parameter
uncertainty through the dynamic model.
plot_dose_response( fit, endpoint = "growth", n_draws = 100, n_conc = 50, dt = 1, t_end = NULL, seed = NULL )plot_dose_response( fit, endpoint = "growth", n_draws = 100, n_conc = 50, dt = 1, t_end = NULL, seed = NULL )
fit |
A |
endpoint |
Which endpoint to plot. Currently only |
n_draws |
Number of posterior draws to use. Default 100. |
n_conc |
Number of concentration points in the continuous grid. Default 50. |
dt |
Euler integration step size (days). Default 1.0. Smaller values are more accurate but slower. The Stan model uses BDF with adaptive stepping; this is an approximation for visualisation. |
t_end |
End time for the simulation (days). Default |
seed |
Integer seed for reproducible draw selection.
Default |
This is a visualisation tool, not exact Stan inference. The
R-side Euler integrator (step size dt) is an approximation of the
BDF solver used during fitting. For quantitative
results, use bdeb_ec50() which extracts the analytically computed
EC and NEC directly from the Stan posterior.
Performance note. Each draw requires n_conc ODE integrations,
so n_draws * n_conc total. With default settings (100 draws,
50 concentrations) this takes a few seconds. Reduce n_draws for
faster interactive use.
A ggplot2 object.
## Not run: data(debtox_growth) dat <- bdeb_data(growth = debtox_growth, concentration = c("1" = 0, "11" = 20, "21" = 80, "31" = 200)) fit <- bdeb_fit(bdeb_tox(dat, stress = "assimilation")) plot_dose_response(fit, n_draws = 50) ## End(Not run)## Not run: data(debtox_growth) dat <- bdeb_data(growth = debtox_growth, concentration = c("1" = 0, "11" = 20, "21" = 80, "31" = 200)) fit <- bdeb_fit(bdeb_tox(dat, stress = "assimilation")) plot_dose_response(fit, n_draws = 50) ## End(Not run)
Visualises the contents of a bdeb_data() object. Growth data are
shown as observed length versus time, with one trace per individual.
Reproduction data are shown as interval counts versus interval
midpoint. When concentration information is available (DEBtox
setups) individuals are coloured by group.
## S3 method for class 'bdeb_data' plot(x, endpoint = NULL, ...)## S3 method for class 'bdeb_data' plot(x, endpoint = NULL, ...)
x |
A |
endpoint |
Which endpoint to plot: |
... |
Ignored. |
A ggplot2::ggplot object.
df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) plot(dat)df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) plot(dat)
Visualises the per-parameter R-hat or ESS-bulk values from a
bdeb_diagnose() object. A dashed red reference line is drawn at the
Vehtari et al. (2021) threshold (R-hat = 1.01, ESS-bulk = 400).
## S3 method for class 'bdeb_diagnostics' plot(x, type = c("rhat", "ess"), ...)## S3 method for class 'bdeb_diagnostics' plot(x, type = c("rhat", "ess"), ...)
x |
A |
type |
One of |
... |
Unused. |
A ggplot2::ggplot object.
## Not run: fit <- bdeb_fit(mod) plot(bdeb_diagnose(fit), type = "ess") ## End(Not run)## Not run: fit <- bdeb_fit(mod) plot(bdeb_diagnose(fit), type = "ess") ## End(Not run)
Plot a BDEB Fit
## S3 method for class 'bdeb_fit' plot( x, type = c("trace", "posterior", "pairs", "trajectory", "prior_posterior"), pars = NULL, n_draws = 100, seed = NULL, ... )## S3 method for class 'bdeb_fit' plot( x, type = c("trace", "posterior", "pairs", "trajectory", "prior_posterior"), pars = NULL, n_draws = 100, seed = NULL, ... )
x |
A |
type |
Type of plot. One of:
|
pars |
Character vector of parameters to plot. Default: core DEB parameters. |
n_draws |
Number of posterior draws for trajectory plots. Default 100. |
seed |
Integer seed for reproducible draw selection in trajectory
plots. Default |
... |
Additional arguments passed to bayesplot functions. |
A ggplot2 object.
## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) plot(fit, type = "trace") plot(fit, type = "trajectory", n_draws = 50) ## End(Not run)## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) plot(fit, type = "trace") plot(fit, type = "trajectory", n_draws = 50) ## End(Not run)
Displays the prior densities for the model parameters as a faceted
panel of curves. Each parameter prior is drawn between the
and quantiles of its prior distribution; for
bounded supports (Beta, half-normal, half-Cauchy, exponential) the
lower bound is fixed at zero (or a small epsilon for densities that
diverge there). Useful for sanity-checking prior choices before
calling bdeb_fit().
## S3 method for class 'bdeb_model' plot(x, pars = NULL, n = 200, ...)## S3 method for class 'bdeb_model' plot(x, pars = NULL, n = 200, ...)
x |
A |
pars |
Optional character vector of parameter names to plot. Default: all priors in the model. |
n |
Number of grid points per density curve. Default 200. |
... |
Ignored. |
A ggplot2::ggplot object.
df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) mod <- bdeb_model(dat, type = "individual") plot(mod, pars = c("p_Am", "kappa"))df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) mod <- bdeb_model(dat, type = "individual") plot(mod, pars = c("p_Am", "kappa"))
Plot Posterior Predictive Checks
## S3 method for class 'bdeb_ppc' plot(x, n_draws = 50, ...)## S3 method for class 'bdeb_ppc' plot(x, n_draws = 50, ...)
x |
A |
n_draws |
Number of replicated trajectories to show. Default 50. |
... |
Ignored. |
A ggplot2 object.
## Not run: fit <- bdeb_fit(mod) plot(bdeb_ppc(fit, type = "growth")) ## End(Not run)## Not run: fit <- bdeb_fit(mod) plot(bdeb_ppc(fit, type = "growth")) ## End(Not run)
Overlays a sample of the posterior trajectory draws stored in a
bdeb_prediction object.
## S3 method for class 'bdeb_prediction' plot(x, n_draws = 100, ...)## S3 method for class 'bdeb_prediction' plot(x, n_draws = 100, ...)
x |
A |
n_draws |
Maximum number of trajectories to overlay. Default 100. |
... |
Unused. |
A ggplot2::ggplot object.
## Not run: fit <- bdeb_fit(mod) plot(predict(fit), n_draws = 50) ## End(Not run)## Not run: fit <- bdeb_fit(mod) plot(predict(fit), n_draws = 50) ## End(Not run)
When newdata = NULL, extracts the fitted trajectories (L_hat)
from the Stan posterior (exact). When newdata is provided, performs
R-side forward simulation (Euler integration) from the posterior
draws under new environmental conditions or extended time horizons.
The Euler integrator is an approximation — for quantitative
results at the original data conditions, prefer newdata = NULL.
## S3 method for class 'bdeb_fit' predict(object, newdata = NULL, n_draws = 200, dt = 0.5, seed = NULL, ...) bdeb_predict(fit, newdata = NULL, n_draws = 200, dt = 0.5, seed = NULL)## S3 method for class 'bdeb_fit' predict(object, newdata = NULL, n_draws = 200, dt = 0.5, seed = NULL, ...) bdeb_predict(fit, newdata = NULL, n_draws = 200, dt = 0.5, seed = NULL)
object |
A |
newdata |
Optional named list with new conditions. Supported fields:
|
n_draws |
Number of posterior draws to use. Default 200. |
dt |
Euler step size for forward simulation (days). Default 0.5. |
seed |
Integer seed for reproducible draw selection.
Default |
... |
Ignored. |
fit |
A |
A bdeb_prediction object with components t (time vector),
L_hat (matrix: draws x time points), n_draws, model_type.
## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) pred <- predict(fit, n_draws = 200) summary(pred); plot(pred) ## End(Not run)## Not run: data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) fit <- bdeb_fit(bdeb_model(dat, type = "individual")) pred <- predict(fit, n_draws = 200) summary(pred); plot(pred) ## End(Not run)
Print a BDEB Data Object
## S3 method for class 'bdeb_data' print(x, ...)## S3 method for class 'bdeb_data' print(x, ...)
x |
A |
... |
Ignored. |
The input object, invisibly.
Default printing for bdeb_diagnose() output. Displays divergence /
treedepth / E-BFMI alerts, R-hat and ESS warnings, and the full
parameter summary table. Output uses cli::cli alerts and is therefore
silenceable via cli::cli_inform() sinks.
## S3 method for class 'bdeb_diagnostics' print(x, ...)## S3 method for class 'bdeb_diagnostics' print(x, ...)
x |
A |
... |
Unused. |
The input object, invisibly.
## Not run: fit <- bdeb_fit(mod) print(bdeb_diagnose(fit)) ## End(Not run)## Not run: fit <- bdeb_fit(mod) print(bdeb_diagnose(fit)) ## End(Not run)
Print a BDEB Fit
## S3 method for class 'bdeb_fit' print(x, ...)## S3 method for class 'bdeb_fit' print(x, ...)
x |
A |
... |
Ignored. |
The input object, invisibly.
Print a BDEB Model Specification
## S3 method for class 'bdeb_model' print(x, ...)## S3 method for class 'bdeb_model' print(x, ...)
x |
A |
... |
Ignored. |
The input object, invisibly.
Print a BDEB Posterior Predictive Check
## S3 method for class 'bdeb_ppc' print(x, ...)## S3 method for class 'bdeb_ppc' print(x, ...)
x |
A |
... |
Ignored. |
The input object, invisibly.
One-line metadata printer for predict.bdeb_fit() output.
## S3 method for class 'bdeb_prediction' print(x, ...)## S3 method for class 'bdeb_prediction' print(x, ...)
x |
A |
... |
Unused. |
The input object, invisibly.
## Not run: fit <- bdeb_fit(mod) print(predict(fit)) ## End(Not run)## Not run: fit <- bdeb_fit(mod) print(predict(fit)) ## End(Not run)
Returns a named list of weakly informative priors for standard DEB
parameters. The defaults are calibrated against the parameter ranges
observed in the Add-my-Pet (AmP) collection (Marques et al., 2018)
for standard ecotoxicological test species. All positive rate
parameters use log-normal priors whose 95 \
roughly one order of magnitude around typical values;
uses which is symmetric on with
prior mean 0.5.
prior_default(type = c("individual", "growth_repro", "hierarchical", "debtox"))prior_default(type = c("individual", "growth_repro", "hierarchical", "debtox"))
type |
One of |
Named list of bdeb_prior objects.
Marques, G.M., Augustine, S., Lika, K., Pecquerie, L., Domingos, T. and Kooijman, S.A.L.M. (2018). The AmP project: comparing species on the basis of dynamic energy budget parameters. PLOS Computational Biology, 14(5), e1006100. doi:10.1371/journal.pcbi.1006100
prior_default("individual")prior_default("individual")
Returns priors calibrated to a specific species using parameter
estimates from the Add-my-Pet (AmP) collection (Marques et al.,
2018). The log-normal priors are centred on the AmP point estimate
(log scale) with a moderate spread () that places
95\
value.
prior_species( species, type = c("individual", "growth_repro", "hierarchical", "debtox") )prior_species( species, type = c("individual", "growth_repro", "hierarchical", "debtox") )
species |
Character string: species name with underscore
separator (e.g., |
type |
Model type for filling model-specific defaults. |
Currently supported species (more will be added):
Eisenia_fetidaCompost earthworm; AmP entry Eisenia_fetida.
Eisenia_andreiSibling species of E. fetida; shares similar DEB parameters.
Folsomia_candidaSpringtail; standard ISO reproduction test species.
Daphnia_magnaWater flea; classic aquatic ecotox model.
Lumbricus_rubellusField earthworm; common biomonitoring species.
Named list of bdeb_prior objects, suitable for the
priors argument of bdeb_model() or bdeb_tox().
Marques, G.M., Augustine, S., Lika, K., Pecquerie, L., Domingos, T. and Kooijman, S.A.L.M. (2018). The AmP project: comparing species on the basis of dynamic energy budget parameters. PLOS Computational Biology, 14(5), e1006100. doi:10.1371/journal.pcbi.1006100
# Use AmP-calibrated priors for E. fetida prior_species("Eisenia_fetida") # Combine with model specification (R-side, no Stan sampling) data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) mod <- bdeb_model(dat, type = "individual", priors = prior_species("Eisenia_fetida"))# Use AmP-calibrated priors for E. fetida prior_species("Eisenia_fetida") # Combine with model specification (R-side, no Stan sampling) data(eisenia_growth) dat <- bdeb_data(growth = eisenia_growth[eisenia_growth$id == 1, ]) mod <- bdeb_model(dat, type = "individual", priors = prior_species("Eisenia_fetida"))
Constructor functions for prior distribution objects used in
bdeb_model(). Each returns a lightweight bdeb_prior S3 object
that encodes the distribution family and its hyperparameters. The
prior is evaluated inside the Stan model block; hyperparameters are
passed as data so that changing priors does not require recompilation.
prior_lognormal(mu = 0, sigma = 1) prior_normal(mu = 0, sigma = 1) prior_beta(a = 2, b = 2) prior_halfnormal(sigma = 1) prior_halfcauchy(sigma = 1) prior_exponential(rate = 1)prior_lognormal(mu = 0, sigma = 1) prior_normal(mu = 0, sigma = 1) prior_beta(a = 2, b = 2) prior_halfnormal(sigma = 1) prior_halfcauchy(sigma = 1) prior_exponential(rate = 1)
mu |
Mean. |
sigma |
Scale of the half-Cauchy. |
a |
Shape parameter alpha. |
b |
Shape parameter beta. |
rate |
Rate parameter (1/mean). |
The choice of prior family follows the recommendations for DEB parameters in Hackenberger (2025, Ch. 6) and general guidelines from Gelman et al. (2013, Sec. 2.9):
Positive rate parameters (, ,
, ) — log-normal, because the log-transform
maps the strictly positive domain to the real line.
Allocation fraction — Beta, the
natural conjugate for bounded parameters.
Observation-error standard deviations — half-normal (or half-Cauchy for heavier tails), which place zero mass on negative values (Gelman, 2006).
Hierarchical standard deviations — exponential, following the advice of Betancourt & Girolami (2015) for non-centred parameterisations.
A bdeb_prior object (list with class "bdeb_prior").
prior_lognormal(): Log-normal prior (for positive parameters: p_Am, p_M, v, E_G, etc.)
prior_normal(): Normal prior (for unconstrained parameters)
prior_beta(): Beta prior (for (0,1)-constrained parameters: kappa)
prior_halfnormal(): Half-normal prior (for scale parameters: sigma_L, etc.)
prior_halfcauchy(): Half-Cauchy prior (for scale parameters, heavier tails)
prior_exponential(): Exponential prior (for variance components in hierarchical models)
Gelman, A. (2006). Prior distributions for variance parameters in hierarchical models. Bayesian Analysis, 1(3), 515–534. doi:10.1214/06-BA117A
Gelman, A., Carlin, J.B., Stern, H.S., Dunson, D.B., Vehtari, A. and Rubin, D.B. (2013). Bayesian Data Analysis. 3rd edition. Chapman & Hall/CRC.
# Log-normal prior on assimilation rate: median ~ exp(1.5) ~ 4.5 prior_lognormal(mu = 1.5, sigma = 0.5) # Beta(2,2) prior on kappa — symmetric, favouring 0.5 prior_beta(a = 2, b = 2)# Log-normal prior on assimilation rate: median ~ exp(1.5) ~ 4.5 prior_lognormal(mu = 1.5, sigma = 0.5) # Beta(2,2) prior on kappa — symmetric, favouring 0.5 prior_beta(a = 2, b = 2)
Many ecotoxicological protocols (e.g., ISO 11267 for Folsomia candida,
OECD 222 for Eisenia fetida) report cumulative offspring counts at
successive observation times. The DEB reproduction buffer model, however,
requires interval counts so that the negative-binomial likelihood can be
applied to each counting period. This function computes the
first-difference per individual.
repro_to_intervals(df)repro_to_intervals(df)
df |
Data frame with columns: |
Data frame with columns: id, t_start, t_end, count.
cumul <- data.frame( id = rep(1, 5), time = c(0, 7, 14, 21, 28), cumulative = c(0, 10, 30, 60, 100) ) repro_to_intervals(cumul)cumul <- data.frame( id = rep(1, 5), time = c(0, 7, 14, 21, 28), cumulative = c(0, 10, 30, 60, 100) ) repro_to_intervals(cumul)
Observed minus fitted length for each observation, using the posterior
point estimate from fitted(). Bayesian counterpart of
stats::residuals().
## S3 method for class 'bdeb_fit' residuals(object, type = "response", ...)## S3 method for class 'bdeb_fit' residuals(object, type = "response", ...)
object |
A |
type |
Currently only |
... |
Ignored. |
Currently supported for "individual" and "growth_repro" models.
Named numeric vector of residuals.
## Not run: fit <- bdeb_fit(mod) residuals(fit) ## End(Not run)## Not run: fit <- bdeb_fit(mod) residuals(fit) ## End(Not run)
Returns a compact list of summary statistics describing a
bdeb_data() object: number of observations, number of unique
individuals, time range, presence of growth/reproduction endpoints,
the functional response, and (for DEBtox data) the unique
concentration levels.
## S3 method for class 'bdeb_data' summary(object, ...) ## S3 method for class 'summary.bdeb_data' print(x, ...)## S3 method for class 'bdeb_data' summary(object, ...) ## S3 method for class 'summary.bdeb_data' print(x, ...)
object |
A |
... |
Ignored. |
x |
A |
An object of class summary.bdeb_data (a list).
df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) summary(dat)df <- data.frame(id = 1, time = 0:5, length = seq(0.1, 0.6, by = 0.1)) dat <- bdeb_data(growth = df) summary(dat)
Returns counts of problematic parameters (divergences, treedepth saturations, low-EBFMI chains, R-hat > 1.01, ESS-bulk < 400) suitable for a one-line health check or programmatic gating.
## S3 method for class 'bdeb_diagnostics' summary(object, ...)## S3 method for class 'bdeb_diagnostics' summary(object, ...)
object |
A |
... |
Unused. |
An object of class summary.bdeb_diagnostics (a list).
## Not run: fit <- bdeb_fit(mod) summary(bdeb_diagnose(fit)) ## End(Not run)## Not run: fit <- bdeb_fit(mod) summary(bdeb_diagnose(fit)) ## End(Not run)
Returns a tidy summary table of posterior draws for model parameters
(and optionally derived quantities), analogous to
stats::summary.lm() for frequentist fits.
## S3 method for class 'bdeb_fit' summary(object, pars = NULL, prob = 0.9, ...)## S3 method for class 'bdeb_fit' summary(object, pars = NULL, prob = 0.9, ...)
object |
A |
pars |
Character vector of parameter names. Default: all model
parameters (excludes |
prob |
Probability for the central credible interval. Default 0.90 (5th/95th percentiles). |
... |
Ignored. |
A posterior::draws_summary data frame with columns
variable, mean, sd, median, two quantile columns named
by their percentile (e.g. "5%" / "95%" for prob = 0.90),
rhat, ess_bulk, and ess_tail.
## Not run: fit <- bdeb_fit(mod) summary(fit, pars = c("p_Am", "kappa"), prob = 0.95) ## End(Not run)## Not run: fit <- bdeb_fit(mod) summary(fit, pars = c("p_Am", "kappa"), prob = 0.95) ## End(Not run)
Returns a list summarising the structure of a bdeb_model() object:
model type, Stan program name, names of model parameters, prior
families, observation models, and (when present) the temperature
correction settings. Useful for one-glance verification before
calling bdeb_fit().
## S3 method for class 'bdeb_model' summary(object, ...) ## S3 method for class 'summary.bdeb_model' print(x, ...)## S3 method for class 'bdeb_model' summary(object, ...) ## S3 method for class 'summary.bdeb_model' print(x, ...)
object |
A |
... |
Ignored. |
x |
A |
An object of class summary.bdeb_model (a list).
Reduces the matrix of posterior trajectory draws stored in a
bdeb_prediction object to per-time-point credible intervals.
## S3 method for class 'bdeb_prediction' summary(object, prob = 0.9, ...)## S3 method for class 'bdeb_prediction' summary(object, prob = 0.9, ...)
object |
A |
prob |
Credible interval coverage in |
... |
Unused. |
A data frame with columns time, lower, median, upper.
Carries class summary.bdeb_prediction and attribute prob.
## Not run: fit <- bdeb_fit(mod) summary(predict(fit), prob = 0.95) ## End(Not run)## Not run: fit <- bdeb_fit(mod) summary(predict(fit), prob = 0.95) ## End(Not run)
Computes the empirical covariance matrix of the posterior draws for
all model parameters. Bayesian counterpart of stats::vcov().
## S3 method for class 'bdeb_fit' vcov(object, ...)## S3 method for class 'bdeb_fit' vcov(object, ...)
object |
A |
... |
Ignored. |
A symmetric numeric matrix with model parameters on rows and columns.
## Not run: fit <- bdeb_fit(mod) vcov(fit) ## End(Not run)## Not run: fit <- bdeb_fit(mod) vcov(fit) ## End(Not run)