Here is an example of how to code the posterior.

# This is a function that takes 4 arguments:
# - fitmodel, a fitmodel object that defines the model dynamics,
#   prior and likelihoods.
# - theta, a named vector of parameters
# - initState,  a named vector of initial state
# - data, the data set we are fitting the model to
# It returns the posterior for the given model, parameters, initial
# state and data.
my_dLogPosterior <- function(fitmodel, theta, initState, data) {
  # calculate the fitmodel prior for parameter vector theta using
  # fitmodel$dPrior, and assign to variable logPrior
  logPrior <- fitmodel$dPrior(theta, log = TRUE)

  # calculate the log-likelihood of `theta`
  # and `initState` with respect to the data using `dTrajObs`
  # and assign to a variable `logLikelihood`
  logLikelihood <- dTrajObs(fitmodel, theta, initState, data, log = TRUE)

  # calulate the log-posterior using the log-prior and log-likelihood
  logPosterior <- logPrior + logLikelihood

  return(logPosterior)
}

You can copy and paste the function into your R session, and proceed from there.

Return to the introductory practical session.

 

This web site and the material contained in it were originally created in support of an annual short course on Model Fitting and Inference for Infectious Disease Dynamics at the London School of Hygiene & Tropical Medicine. All material is under a MIT license. Please report any issues or suggestions for improvement on the corresponding GitHub issue tracker. We are always keen to hear about any uses of the material here, so please do get in touch using the Discussion board if you have any questions or ideas, or if you find the material here useful or use it in your own teaching.