% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fit.R
\name{bdeb_fit}
\alias{bdeb_fit}
\title{Fit a BDEB Model via Hamiltonian Monte Carlo}
\usage{
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"),
  ...
)
}
\arguments{
\item{model}{A \code{\link[=bdeb_model]{bdeb_model()}} object.}

\item{chains}{Number of independent MCMC chains. Default 4 (the minimum
recommended by Vehtari et al., 2021, for reliable \eqn{\hat{R}}).}

\item{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.}

\item{iter_sampling}{Number of post-warmup sampling iterations per chain.
Default 1000 (yielding 4000 total draws with 4 chains).}

\item{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.}

\item{max_treedepth}{Maximum binary-tree depth for NUTS.  Default 10
(i.e., up to \eqn{2^{10} = 1024} leapfrog steps per transition).}

\item{seed}{Integer random seed for full reproducibility.}

\item{parallel_chains}{Number of chains to run in parallel.
Default \code{min(chains, detectCores() - 1)}.}

\item{threads_per_chain}{Number of threads per chain for within-chain
parallelism via Stan's \code{reduce_sum}.  Default \code{NULL} (no threading;
the model runs sequentially within each chain).  Set to e.g.
4 for the \code{"hierarchical"} or \code{"debtox"} models to distribute
per-individual / per-group ODE solves across threads.  When
threading is active, adjust \code{parallel_chains} so that
\code{chains * threads_per_chain} does not exceed available cores.
Has no effect on \code{"individual"} or \code{"growth_repro"} models
(single ODE solve, nothing to distribute).}

\item{refresh}{How often to print sampling progress (iterations).
Default 200.  Set to 0 for silent operation.}

\item{algorithm}{One of \code{"sampling"} (default; full HMC via NUTS) or
\code{"variational"} (mean-field automatic differentiation variational
inference, ADVI).  ADVI is \strong{substantially faster} but yields an
\emph{approximation} of the posterior, not an exact draw.  Use it for
illustrative or exploratory work; \strong{always use the default
\code{"sampling"} for publication-grade inference}.  When
\code{algorithm = "variational"}, the arguments \code{chains},
\code{iter_warmup}, \code{iter_sampling}, \code{adapt_delta}, \code{max_treedepth},
and \code{parallel_chains} are ignored; ADVI-specific defaults are
used instead (1000 output samples).  Diagnostics that depend on
chain mixing (R-hat, divergences, treedepth) are not defined for
ADVI fits, and \code{\link[=bdeb_diagnose]{bdeb_diagnose()}} will refuse to run on them.}

\item{...}{Additional arguments forwarded to \code{CmdStanModel$sample()}
(or \code{CmdStanModel$variational()} when \code{algorithm = "variational"}).}
}
\value{
A \code{bdeb_fit} object containing the \code{CmdStanMCMC} (or
\code{CmdStanVB}) result, the model specification, and sampling
metadata.  The list element \code{algorithm} records which inference
engine was used.
}
\description{
Compiles the bundled Stan program via \pkg{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 (\code{ode_bdf}) with absolute and relative
tolerances of \eqn{10^{-6}}.
}
\details{
\strong{Tuning guidance.} If \code{\link[=bdeb_diagnose]{bdeb_diagnose()}} reports divergent transitions,
increase \code{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
\code{max_treedepth} (e.g., 12 or 15).  For hierarchical models, starting
values can matter; the non-centred parameterisation used in
\code{bdeb_hierarchical_growth.stan} should suffice in most cases.
}
\section{Notes on Stan informational messages}{

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 \code{ode_bdf_tol} with \code{max_num_steps = 1e5}
(raised from \code{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 \strong{benign} as long
as \code{\link[=bdeb_diagnose]{bdeb_diagnose()}} reports no divergent transitions, no max
treedepth saturation, and adequate \eqn{\hat{R}}/ESS for all
parameters.
}

\examples{
# 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().
\donttest{
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)
}
}
}
\references{
Hoffman, M.D. and Gelman, A. (2014). The No-U-Turn Sampler:
adaptively setting path lengths in Hamiltonian Monte Carlo.
\emph{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 \eqn{\hat{R}} for assessing convergence of MCMC.
\emph{Bayesian Analysis}, 16(2), 667--718. \doi{10.1214/20-BA1221}
}
