A wrapper around run.jags that simplifies fitting 'JAGS' models with usage with pre-specified model part of the 'JAGS' syntax, data and list of prior distributions.

JAGS_fit(
  model_syntax,
  data = NULL,
  prior_list = NULL,
  formula_list = NULL,
  formula_data_list = NULL,
  formula_prior_list = NULL,
  formula_scale_list = NULL,
  chains = 4,
  adapt = 500,
  burnin = 1000,
  sample = 4000,
  thin = 1,
  autofit = FALSE,
  autofit_control = list(max_Rhat = 1.05, min_ESS = 500, max_error = 0.01, max_SD_error =
    0.05, max_time = list(time = 60, unit = "mins"), sample_extend = 1000, restarts = 10,
    max_extend = 10, check_indicators = FALSE, monitor = NULL, allow_not_assessable =
    FALSE),
  parallel = FALSE,
  cores = chains,
  silent = TRUE,
  seed = NULL,
  add_parameters = NULL,
  required_packages = NULL,
  formula_random_prior_list = NULL,
  formula_random_effects_compile_list = NULL,
  jags_modules = NULL,
  runtime_setup = NULL,
  runtime_cache = NULL,
  worker_output = NULL,
  ...
)

JAGS_extend(
  fit,
  autofit_control = list(max_Rhat = 1.05, min_ESS = 500, max_error = 0.01, max_SD_error =
    0.05, max_time = list(time = 60, unit = "mins"), sample_extend = 1000, restarts = 10,
    max_extend = 10, check_indicators = FALSE, monitor = NULL, allow_not_assessable =
    FALSE),
  parallel = FALSE,
  cores = NULL,
  silent = TRUE,
  runtime_setup = attr(fit, "runtime_setup", exact = TRUE),
  runtime_cache = attr(fit, "runtime_cache", exact = TRUE),
  worker_output = NULL
)

Arguments

model_syntax

jags syntax for the model part

data

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

prior_list

named list of prior distribution (names correspond to the parameter names) of parameters not specified within the formula_list. Factor priors must carry their levels, set with prior_factor_levels().

formula_list

named list of formulas to be added to the model (names correspond to the parameter name created by each of the formula)

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 of the formula)

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 NULL (no standardization).

chains

number of chains to be run, defaults to 4

adapt

number of samples used for adapting the MCMC chains, defaults to 500

burnin

number of burnin iterations of the MCMC chains, defaults to 1000

sample

number of sampling iterations of the MCMC chains, defaults to 4000

thin

thinning interval for the MCMC samples, defaults to 1

autofit

whether the models should be refitted until convergence criteria specified in autofit_control. Defaults to FALSE.

autofit_control

a list of arguments controlling the autofit function. Convergence thresholds and max_time$time must be finite and non-missing. Set a convergence threshold or max_time to NULL to disable that check. Possible options are:

max_Rhat

maximum R-hat error for the autofit function. Defaults to 1.05. R-hat is the larger of the point estimate and the upper confidence limit of the potential scale reduction factor, whereas the summary tables show the point estimate (see JAGS_check_convergence()).

min_ESS

minimum effective sample size. Defaults to 500.

max_error

maximum MCMC error. Defaults to 0.01.

max_SD_error

maximum MCMC error as the proportion of standard deviation of the parameters. Defaults to 0.05.

max_time

list with fields time and unit, specifying when the automatic fitting function is stopped. The unit value corresponds to the units argument of difftime.

max_extend

number of times after which the automatic fitting function is stopped.

sample_extend

number of samples between each convergence check. Defaults to 1000.

restarts

maximum number of fitting attempts when the model fails to initialize; every failed attempt but the last is retried with new initial values (restarts = 1 fits once, without a retry). A failed attempt that is retried is reported as a warning of the fit. Defaults to 10.

check_indicators

whether model indicator variables should be included in convergence checks, including when monitor selects a narrower parameter set. Auxiliary inclusion-probability coordinates remain excluded unless requested explicitly. Defaults to FALSE.

monitor

optional character vector selecting parameters for convergence checks. Base names select all indexed elements. Requests are resolved against the monitored nodes that the summary tables show, including the derived and auxiliary ones that the default selection excludes. Base names that are not monitored are rejected before sampling (error class BayesTools_parameter_not_found); an indexed element such as "mu[2]" is resolved against the fitted columns after the first run and fails then when it does not exist. Defaults to NULL, which checks the default selection of JAGS_check_convergence(): the sampled parameters of the priors, add_parameters that depend on a stochastic node, and the stochastic nodes that formulas monitor (such as latent random effects and LKJ primitives). Deterministic nodes that formulas monitor (such as random-effect correlation matrices and their Cholesky factors) are derived and not checked by default. The role of every fitted coordinate is stored in the convergence_role column of parameter_coordinates().

allow_not_assessable

whether undefined diagnostics for requested sampled parameters may be ignored. Defaults to FALSE.

parallel

whether the chains should be run in parallel FALSE

cores

number of cores used for multithreading if parallel = TRUE, defaults to chains

silent

whether the function should proceed silently, defaults to TRUE

seed

seed for random number generation by JAGS_fit(): an integer between -.Machine$integer.max and .Machine$integer.max. Draws are reproducible for the same seed, chains, and R random-number generator settings (RNGkind()), and, with parallel = TRUE, the same cores. Parallel draws need not equal serial draws with the same seed, because the backend passes each chain's initial state to its worker in a serialized text form. Initial values are drawn from the priors after set.seed(seed), and each chain's JAGS random-number seed is drawn from the same seed with sample.int(.Machine$integer.max, chains) (see JAGS_get_inits). A chain's JAGS seed therefore does not depend on the number of chains, but the JAGS generator does: with more than four chains it changes from "base::Super-Duper" to "lecuyer::RngStream", so the draws of a chain differ between fits with up to four and with more chains. The chains of adjacent seeds (e.g., seed and seed + 1) do not share random-number streams. Automatic restarts after a failed initialization (see restarts in autofit_control) draw their seeds from a separate stream of the same seed (the first L'Ecuyer-CMRG substream), so the i-th restart does not repeat the fit with seed + i. A seeded fit restores the caller's random-number state (.Random.seed and RNGkind()) when it returns. With seed = NULL, the initial values are drawn from one seed taken from the caller's random-number stream (see JAGS_get_inits), which the fit then continues to use.

add_parameters

vector of additional parameter names that should be monitored but were not specified in the prior_list. Automatic fitting checks their convergence like that of the other parameters. Fully observed data and a node that the model syntax defines deterministically (<- or =) from data and constants only are structural constants and do not block convergence. A node that is stochastic (~) or depends on a stochastic node is checked, and its constant draws are not assessable (see autofit_control$allow_not_assessable). A name that repeats a parameter of prior_list is refused. A parameter that a formula needs monitored, such as the scalar SD source of a random-effect block (random_sd_source("tau")), is added automatically and, when prior_list already holds its prior, is monitored through that prior.

required_packages

character vector specifying list of packages containing JAGS models required for sampling (in case that the function is run in parallel or in detached R session). Defaults to NULL. Parallel workers must load the same versions and native library builds as the parent session. When developing packages with load_all(), install matching builds into a library and set R_LIBS_USER before starting R and its workers.

formula_random_prior_list

optional named list of prior_random() objects for random effects in formula_list. Required for any formula that contains random effects.

formula_random_effects_compile_list

optional named list of random_effects_compile() objects controlling which formula random-effect blocks are sampled and which are compiled as marginalized structural blocks. Defaults to NULL, which preserves the current all-sampled behavior.

jags_modules

character vector specifying JAGS modules required by the generated model syntax. Defaults to NULL.

runtime_setup

optional function accepting one context list. After required packages and JAGS modules load, it is called with phase = "start" in the calling process, then each parallel worker. The context contains role ("local", "coordinator", or "worker"), chains (total chains), processes (sampling processes), process_id (one-based worker index, or zero for the coordinator), process_chains (chains assigned to this process; zero for the coordinator), and parallel. Chains are divided round-robin among at most min(cores, chains) workers. On exit, including fitting failures, workers are stopped before the calling process receives phase = "finish" with its original topology context. Worker processes do not receive a finish callback. If stopping workers fails, a warning is issued and the finish callback is not run; cleanup still attempts every remaining worker and closes failed connections. This permits releasing coordinator resources before parallel work and restoring them afterward. Return values are ignored. The callback must be idempotent, must not change random-number generator state, and should capture only small immutable settings. Packages it uses must be included in required_packages. The callback is stored with the fit; JAGS_extend() reuses it with the current chain and worker topology. Supplying NULL explicitly disables replay.

runtime_cache

optional function accepting context and state = NULL for optional computational caches. It must not change inference targets or random-number state and must capture only small settings. After runtime setup, a fit or extension calls it with context$phase = "restore" and a list of prior process shards assigned to this process (empty for new fits or workers without an assigned shard). Each prior shard is sent to at most one current process, in round-robin order; shards are not duplicated when worker count increases. Before workers stop, a completed fit calls it with context$phase = "capture" and state = NULL. Capture returns one serializable shard, or NULL to retain no state. The fitted object's runtime_state attribute stores process shards separately from its small runtime_cache callback. Backend extension calls receive neither attribute. JAGS_extend() restores old state independently of whether its callback elects to capture fresh state. Callback warnings and errors are reported without discarding valid draws; a failed capture callback leaves a NULL shard for its process. If a worker connection fails during capture, no shard is retained from any process for that fit. Capture warnings, including such failures, are also recorded in the fit's warnings attribute. Error and interrupt cleanup does not attempt capture; ordinary runtime cleanup still runs. Retained R snapshots, serialization buffers, and the caller's old fitted object consume memory in addition to active cache storage. Callback packages must be listed in required_packages. Passing NULL disables capture and restore.

worker_output

optional file path for parallel worker stdout and stderr. The parent directory must exist. Workers append to the same file, so messages can interleave. NULL retains the backend default of discarding worker output. This setting is call-specific and is not retained with the fit; supply it again to JAGS_extend() when needed. Connection failures stop automatic fitting retries and preserve the original backend error.

...

additional hidden arguments

fit

a 'BayesTools_fit' object (created by JAGS_fit() function) to be extended. A derived-draw view signals BayesTools_draws_view_sampling_unavailable, also BayesTools_sampling_unavailable and BayesTools_draws_view_unavailable, before runtime arguments are forced; extend its original_fit and regenerate it with JAGS_with_draws(). Fits without the parameter map and fit contract of this version of BayesTools (such as fits created by BayesTools 0.3.0) must be refitted: they stop with an error of class BayesTools_refit_required (see JAGS_validate_fit_contract()).

Value

JAGS_fit returns an object of class 'runjags' and 'BayesTools_fit'. JAGS_extend continues the backend random-number generator state of the existing chains; it does not reseed them. Stored parameter and RNG states initialize reconstruction; recompilation can reset sampler tuning and follows runjags' adaptation policy. The model is always recompiled from these stored states, never continued from a compiled model left in the session, so extending the same object twice, or a saved and reloaded copy of it, gives identical draws. Neither function keeps runjags' compiled rjags model (method.options$rjags) in the returned object; runjags::extend.jags() recompiles a model without it, as after reloading.

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