A wrapper around bridge_sampler that automatically computes likelihood part dependent on the prior distribution and prepares parameter samples. log_posterior must specify a function that takes a named parameter list, the data, and any additional arguments, and returns the log likelihood of the model part.

JAGS_bridgesampling(
  fit,
  log_posterior,
  data = NULL,
  prior_list = NULL,
  formula_list = NULL,
  formula_data_list = NULL,
  formula_prior_list = NULL,
  formula_scale_list = NULL,
  add_parameters = NULL,
  add_bounds = NULL,
  maxiter = 10000,
  silent = TRUE,
  formula_random_prior_list = NULL,
  formula_random_effects_compile_list = NULL,
  formula_random_effects_marginalize_list = NULL,
  bridge_context = FALSE,
  bridge_context_node_names = NULL,
  repetitions = 1L,
  method = c("normal", "warp3"),
  nonfinite = c("error", "drop"),
  cores = 1,
  seed = NULL,
  ...
)

Arguments

fit

model fitted with runjags, or posterior samples obtained with rjags-package. Derived-draw views are refused with BayesTools_draws_view_inference_unavailable (also BayesTools_draws_view_unavailable); use fit$original_fit.

log_posterior

function that takes a named list of samples, the data, and additional list of parameters passed as ... as input and returns the log of the unnormalized posterior density of the model part

data

list containing data to fit the model (not including data for the formulas)

prior_list

named list of prior distributions (names correspond to the parameter names) of parameters not specified within the formula_list. For BayesTools_fit objects, stored non-formula priors are used when prior_list = NULL; a supplied prior must specify the same prior as the stored prior of the same name (distribution, parameters, truncation, multiply_by, and mixture components and weights; an error of class BayesTools_refit_required otherwise), while stored priors omitted from prior_list stay allowed. Formula priors are taken from the stored formula metadata: a formula prior supplied here is ignored when it specifies the same prior as the fitted formula prior (distribution, parameters, truncation, contrast, multiply_by, and mixture components and weights) and is an error otherwise.

formula_list

named list of formulas to be added to the model (names correspond to the parameter name created by each of the formula). For BayesTools_fit objects with stored formula-design metadata, formula inputs can be omitted; if supplied, they are rebuilt only to check exact consistency with the fitted design and never replace fitted replay metadata. Fits without versioned formula-design metadata must be refitted: they stop with an error of class BayesTools_refit_required (see JAGS_validate_fit_contract()).

formula_data_list

named list of data frames containing data for each formula (names of the lists correspond to the parameter name created by each formula). When supplied for a fitted formula, these data must exactly match the fitted original-scale formula source snapshot.

formula_prior_list

named list of named lists of prior distributions (names of the lists correspond to the parameter name created by each of the formula and the names of the prior distribution correspond to the parameter names) of parameters specified within the formula

formula_scale_list

named list of named lists for standardizing continuous predictors (names of the lists correspond to the parameter name created by each of the formula). Each entry should be a named list where continuous predictors with TRUE values will be standardized. Defaults to stored fit metadata when available and to NULL (no standardization) otherwise.

add_parameters

character vector of additional monitored posterior parameter names to include in the bridge-sampling state and in the parameters object passed to log_posterior. These are for free stochastic JAGS nodes that are not owned by prior_list, such as special likelihood parameters, and log_posterior must add their prior density. Deterministic nodes computed from other parameters are not valid bridge coordinates; reconstruct them inside log_posterior or, for row-shaped external SD sources, with a parameter_source(values = ...) callback. Linearly dependent bridge coordinate draws are rejected. The parameters object is a named superset of prior-owned and additional values; user code should index it by name, for example parameters[["tau"]]. Parameters already covered by prior_list must not be listed here. For Dirichlet priors generated through BayesTools, add the monitored auxiliary prior_par_eta_* coordinates when needed, not the normalized simplex coordinates owned by the prior.

add_bounds

list with two named numeric vectors, "lb" and "ub", containing lower and upper bounds for every add_parameters entry. The vectors are named by the add_parameters entries (every entry, no others), contain no NA, and satisfy lb < ub; -Inf and Inf are allowed. Must be supplied whenever add_parameters is non-empty. Bounds of the coordinates BayesTools adds for formula random effects are inferred; a supplied bound for such a coordinate must agree with the inferred one.

maxiter

maximum number of iterations for the bridge_sampler

silent

whether the bridge-sampling progress output is suppressed, defaults to TRUE. Known iteration counts exceeding maxiter always signal a diagnostic warning, independently of progress output.

formula_random_prior_list

optional named list of prior_random() objects for random effects in formula_list. Bridge sampling for formula random effects requires the prior_random() interface because the stochastic bridge coordinates are the standardized latent effects and correlation primitives; a fit without their posterior samples (random_monitor(latent = TRUE)) stops with an error of class BayesTools_refit_monitoring (also BayesTools_refit_required). For BayesTools_fit objects with stored formula-design metadata, this can be omitted unless formula inputs are being supplied for a strict consistency check. Supplied callbacks never replace callbacks stored in the fitted formula design.

formula_random_effects_compile_list

optional named list of random_effects_compile() objects. When formula inputs are supplied for bridge-sampling rebuild/validation, this must match the fitted random-effect compilation policy; otherwise a fitted marginalized model would not be rebuilt as the same model.

formula_random_effects_marginalize_list

optional named list identifying fitted formula random-effect blocks whose covariance is required by the bridge target. Selected sampled blocks are integrated analytically only in the bridge target; blocks already fitted as marginalized expose the same covariance contract without changing the fitted model. Each formula-parameter entry can be a character vector of block names, which requests a dense covariance, or a named list with blocks and optional row_blocks. row_blocks must partition the formula rows and may not separate any structurally nonzero selected random-effect covariance; it requests the exact factorized block representation described below. With row_blocks, factor_state = TRUE additionally requests a compact exact contract that separates invariant factor plans from draw-varying coefficient factors and row scales. Every selected sampled Gaussian latent block is removed from the bridge coordinates and formula predictor. Already-marginalized blocks have no latent coordinates to remove. All SD, allocation, correlation, and other covariance parameters and their priors remain in the target. This requires bridge_context = "marginal" or the full context. The likelihood callback is responsible for adding the supplied covariance to its observation covariance.

bridge_context

whether the log_posterior callback receives a read-only bridge_context argument. Defaults to FALSE, preserving the historical log_posterior(parameters, data, ...) call. TRUE supplies the complete context. "nodes" supplies a lightweight context containing only its exact flat named nodes vector. "marginal" supplies those nodes plus exact observation-level covariance contributions for bridge-marginalized Gaussian random effects. A context contains the current independent bridge state and BayesTools-resolved deterministic formula/random-effect nodes; it is not necessarily an original MCMC posterior row. For a formula block fitted with random_effects_compile(marginalized = ...), the SD coordinates and priors stay in the bridge target, but without a context (FALSE, the default) the callback receives neither the SD values nor the covariance: it must reconstruct them from primitive coordinates (add_parameters or its own evaluator) or request "marginal" or "full" (TRUE); the evidence of a callback that ignores the fitted random-effect covariance is the evidence of a model without it.

bridge_context_node_names

optional character vector selecting an exact subset of the complete context's named nodes vector for bridge_context = "nodes" or "marginal". The default, NULL, retains every node. The complete context cannot be subset. Missing requested names are errors.

repetitions

number of independent bridge-sampling repetitions.

method

bridge transformation passed to bridge_sampler; either "normal" or "warp3".

nonfinite

handling of non-finite repetition-level log marginal likelihoods. The default, "error", aborts with an error of class BayesTools_marglik_repetition_failure that names the cause of every failed repetition. "drop" aggregates only the remaining finite repetitions, emits a warning, and records every excluded repetition in the returned diagnostics; it stops with the same error class when no repetition is finite.

cores

number of cores used by bridge_sampler. Defaults to one. Parallel workers must be able to load every package used by log_posterior; these can be supplied through the upstream packages argument in ....

seed

optional integer seed for the random bridge-sampling proposal draws. The caller's random-number state (.Random.seed and RNGkind()) is restored afterwards. The default, NULL, draws from the caller's random-number stream, so the estimate depends on that stream.

...

additional argument to the bridge_sampler and log_posterior function. The upstream-only use_neff logical control defaults to TRUE; an explicitly supplied value is passed to the sampler. The upstream-only controls packages, use_neff, varlist, envir, rcppFile, param_types, and verbose are not forwarded to log_posterior, including for exact zero-dimensional evaluation. Warnings signaled in the calling R process while evaluating callback arguments or the callback body are recorded in diagnostics$upstream_warnings and muffled on both the exact and sampler routes. Callback warnings from parallel worker processes are not relayed to this diagnostic field. Errors retain the Bridge sampling failed: context.

Value

A BayesTools_marglik object that also has the class bridge of released versions, so that bridgesampling::bf(), post_prob() and logml() apply to it. For a single repetition, niter and method of the upstream result are kept at the top level, and the result prints as that object did (one line added when maxiter was exceeded). Failed, manual, exact and repeated results print a BayesTools summary. summary() and bridgesampling::error_measures() of a result forward to the sampler result stored in diagnostics$upstream (the bridge summary and error measures of one repetition, the bridge_list ones of repetitions); a failed, manual or exact result stores none and stops with an error of class BayesTools_marglik_sampler_result_unavailable (parent BayesTools_marglik_unavailable). logml is one scalar natural-log marginal likelihood, aggregated as the median of finite repetition-level log marginal likelihoods. repetitions contains one diagnostic row per bridge repetition, aggregation records the aggregation and failure policy, and diagnostics$upstream retains the original bridgesampling result. Top-level success records estimate availability. The separate logical iteration_limit_exceeded is TRUE when any known repetition count exceeds maxiter, FALSE when all counts are known and none exceeds it, and NA when counts are unavailable or partly unknown without a known excess. Manual/imported and exact zero-dimensional results have NA; historical schema-1 objects may omit the field, meaning unavailable telemetry. This flag does not assert convergence: counts can include upstream retries, including a successful retry whose total count exceeds maxiter.

The columns of repetitions are repetition, logml, niter (iterations used), mcse (Monte Carlo standard error of logml), finite (whether logml is finite), within_maxiter (whether niter did not exceed maxiter; TRUE when the iteration count is unknown), success (finite and within_maxiter), warning and error (the description of an exceeded iteration limit or of a non-finite estimate, NA otherwise), method, n_chains, and n_draws. Only non-finite repetitions are excluded from the aggregate, so aggregation$n_included counts the finite repetitions: a finite repetition that exceeded maxiter has success = FALSE and is still aggregated. Known excess counts always warn with class BayesTools_marglik_iteration_limit (parent BayesTools_marglik_diagnostic; fields repetitions, the affected diagnostic rows, maxiter, and upstream_warnings). A flagged result also prints a visible iteration-count diagnostic. Finite aggregation and top-level success availability are unchanged; legacy repetition success and within_maxiter retain their unknown-count convention.

Rank refusals have class BayesTools_marglik_rank_deficiency (parent BayesTools_marglik_input), with fields reason, rank, n_coordinates, n_draws, and dependent_coordinates. These describe the finite, varying diagnostic sample checked by the existing QR tolerance. The reason "insufficient_draws" means that n_draws <= n_coordinates prevents full centered rank; "dependent_coordinates" means observed numerical rank loss despite a sufficient raw row count. These observations are nonexclusive and neither certifies a structural cause or a guaranteed remedy. Duplicate rows remain counted. Coordinate names are the complete, basis-dependent QR-pivot tail when available, otherwise character(0); they do not identify uniquely faulty or deterministic nodes.

Condition classes: a non-finite repetition under nonfinite = "error", and the absence of any finite repetition under "drop", stop with an error of class BayesTools_marglik_repetition_failure (fields repetitions, the failed rows, and upstream_warnings). Errors of the likelihood callback keep their own classes and fields, with the Bridge sampling failed: context in the message and the muffled warnings in upstream_warnings. A state outside the support of the model (for example an out-of-support row-indexed random-effect SD source value) signals an error of class BayesTools_marglik_out_of_support while the parameters are reconstructed; the bridge target treats it as zero density, and the direct reconstruction functions (such as JAGS_marglik_parameters_formula()) let it escape. The two classes belong to no shared parent class; callers match the class, not the message.

A NA returned by log_posterior on the sampler route is no density. At a posterior draw the model cannot be evaluated where it was sampled: the call stops with an error of class BayesTools_marglik_callback_na (parent class BayesTools_marglik_input; field n_posterior_na, the number of affected posterior draws, and upstream_warnings). At a proposal draw the NA is evaluated as -Inf (zero density) and the call signals a warning of the same classes that reports the share of proposal draws (fields n_proposal_na and n_proposal); the estimate and its success are not otherwise affected. The counts are those that bridgesampling reports for the replaced evaluations. The exact zero-dimensional evaluation and NA priors keep their own errors.

This policy is defined for method = "normal"; method = "warp3" is outside it. bridgesampling evaluates the callback at warped draws and takes their exponentials in extended-range arithmetic, which stops on an NA with the unclassed upstream error "Bridge sampling failed: NAs are not allowed in subscripted assignments" (no BayesTools_marglik_callback_na), and the warnings that it words for warp3 evaluations are not classified either. A callback used with warp3 must not return NA.

Details

Row-shaped external random-effect SD sources, such as random_sd_source("tau", shape = "row"), must be reconstructable during bridge sampling. A source computed from other parameters, for example tau[i] <- s * tau_data[i], is deterministic and must be supplied as parameter_source("tau", shape = "row", values = function(parameters, data, n_rows) ..., inputs = ...). The values function is evaluated from the parameters it declares in inputs and the original-scale formula data stored at fit time; it must return finite, non-negative row values on the support of the model. Any callback data must therefore be included in formula_data_list when fitting. Data supplied only to JAGS_bridgesampling() do not extend or replace the fitted source snapshot. Posterior columns named tau[1], ..., tau[n] with non-negative lower bounds in add_bounds are valid only when every tau[i] is a free stochastic node whose prior density log_posterior adds. Supplying deterministic nodes as bridge coordinates makes the target improper; such rank-deficient bridge coordinate draws are rejected with an error. Rank is checked both on the supplied coordinates before bound transformations and on the transformed coordinates used by the proposal. Each rank check rescales a local diagnostic copy of finite, nonzero columns before standardization to avoid variance overflow or underflow. Supplied coordinates and sampler bounds retain their original values. Constant columns retain their existing sampler handling.

If every bridge coordinate is fixed by a point prior, JAGS_bridgesampling() evaluates log_posterior once at the reconstructed fixed parameter values. The returned marginal likelihood is exact and uses the aggregation rule "exact_zero_dimensional"; no bridge repetitions are performed. A target that declares no coordinate at all (no non-formula prior, formula prior, or add_parameters entry, for example raw draws with prior_list omitted) is an error of class BayesTools_marglik_input, not an exact evaluation.

use_neff is passed to bridge_sampler as the logical flag that upstream defines. bridgesampling computes the effective sample size itself, from the merged integrand matrix, and accepts no caller-supplied value: a numeric use_neff is a length->1 condition upstream and aborts the sampler. Per-chain effective sample sizes therefore cannot be injected here; the merged-chain ESS is conservative, because concatenating chains that have not mixed inflates the estimated autocorrelation and so lowers the ESS.

When bridge_context = TRUE, the callback receives an object of class BayesTools_bridge_context with fields state, state_matrix, nodes, prior_parameters, formula_prior_parameters, formula_parameters, add_parameters, random, marginalized_random, node_info, and metadata. The state field contains the independent bridge coordinates and the completed fixed-zero random-effect latents (latent coordinates of fixed-zero blocks, which are not bridge dimensions). The add_parameters field contains only the add_parameters supplied by the caller: the coordinates BayesTools adds for formula random effects (standardized latent effects and correlation primitives) are not additional parameters, so a callback that adds densities for additional parameters does not count them twice. They are part of state and nodes, and node_info labels them source = "random_latent", owner = "formula", role = "random_latent". The nodes field is a flat named numeric vector that also includes deterministic BayesTools-resolved nodes such as normalized Dirichlet allocation weights reconstructed from prior_par_eta_* coordinates. The node_info field records the owner and role of each exposed node. The random field contains structured random-effect block state including resolved SDs, allocation weights, correlations, Cholesky factors, covariance matrices where row-invariant, and row-indexed SD source values where applicable. Each random block is keyed by formula parameter and block name, and contains block_name, compile_mode, dimensions, levels, scale, allocation, correlation, covariance, latent, and nodes fields.

When bridge_context = "nodes", the callback receives an object inheriting from BayesTools_bridge_context with only the nodes field. Its values and names are identical to the nodes field in the complete context for the same bridge state. Random-effect replay metadata that is invariant across states is compiled once before bridge sampling.

When bridge_context = "marginal", the callback receives the same exact nodes vector plus marginalized_random. If bridge_context_node_names is supplied, nodes is the requested exact subset in the requested order. The latter is keyed by formula parameter and contains representation, blocks, structures, row_names, and dimension. Without row_blocks, representation = "dense" and the covariance field equals the sum of \(ZGZ'\) over exactly the requested random-effect blocks. With validated row_blocks, representation = "factor"; row_blocks gives the exact observation partition and factors contains dense, ordinary grouped \(Z_b G_b Z_b'\), or known-group covariance factors. This avoids materializing zero cross-block entries. For requests with factor_state = TRUE, the marginal context instead reports representation = "factor_state", with invariant factor_plans and draw-varying factor_states; the complete context and direct covariance evaluator retain the full representation. All representations define the same covariance without approximation.

Examples

if (FALSE) { # \dontrun{
# simulate data
set.seed(1)
data <- list(
  x = rnorm(10),
  N = 10
)
data$x

# define priors
priors_list <- list(mu = prior("normal", list(0, 1)))

# define likelihood for the data
model_syntax <-
  "model{
    for(i in 1:N){
      x[i] ~ dnorm(mu, 1)
    }
  }"

# fit the models
fit <- JAGS_fit(model_syntax, data, priors_list, seed = 1)

# define log posterior for bridge sampling
log_posterior <- function(parameters, data){
  sum(dnorm(data$x, parameters$mu, 1, log = TRUE))
}

# get marginal likelihoods
marglik <- JAGS_bridgesampling(
  fit, log_posterior, data, priors_list, seed = 1
)
} # }