The objects fmcmc_kernels are environments that in general contain the
following objects:
proposal: The function used to propose changes in the chain based
on the current state. The function must return a vector of length equal
to the number of parameters in the model.
logratio: This function is called after a new state has been proposed,
and is used to compute the log of the Hastings ratio.
In the case that the logratio function is not specified, then it is assumed
that the transition kernel is symmetric, this is, log-ratio is then implemented
as function(env) {env$f1 - env$f0}
...: Further objects that are used within those functions.
Both functions, proposal and logratio, receive a single argument, an
environment, which is passed by the MCMC() function during each step using
the function environment().
The passed environment is actually the environment in which the MCMC
function is running, in particular, this environment contains the following
objects:
| Object | | Description |
i | | Integer. The current iteration. |
theta1 | | Numeric vector. The last proposed state. |
theta0 | | Numeric vector. The current state |
f | | The log-unnormalized posterior function (a wrapper of fun passed
to MCMC). |
f1 | | The last value of f(theta1) |
f0 | | The last value of f(theta0) |
kernel | | The actual fmcmc_kernel object. |
ans | | The matrix of samples defined up to i - 1. |
These are the core component of the MCMC function. The following block
of code is how this is actually implemented in the package:
for (i in 1L:nsteps) {
# Step 1. Propose
theta1[] <- kernel$proposal(environment())
f1 <- f(theta1)
# Checking f(theta1) (it must be a number, can be Inf)
if (is.nan(f1) | is.na(f1) | is.null(f1))
stop(
"fun(par) is undefined (", f1, ")",
"Check either -fun- or the -lb- and -ub- parameters.",
call. = FALSE
)
# Step 2. Hastings ratio
if (R[i] < kernel$logratio(environment())) {
theta0 <- theta1
f0 <- f1
}
# Step 3. Saving the state
ans[i,] <- theta0
}
For an extensive example on how to create new kernel objects see the vignette
vignette("user-defined-kernels", "fmcmc").