Below, you can find an example of how to code the posterior. Some bits are left out for you to fill in (marked “INSERT HERE”). Each “INSERT HERE” statement requires one line of code. If you struggle, you can find a link to the solution below the function.

# 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 should return the posterior for the given model, parameters,
# initial state and data.
my_dLogPosterior <- function(fitmodel, theta, initState, data) {

    logPrior <- # INSERT HERE: calculate the fitmodel log-prior
        # of `theta` using `fitmodel$dPrior`, and assign
        # to variable `logPrior`

    logLikelihood <- # INSERT HERE: calculate the log-likelihood of `theta`
        # and `initState` with respect to the data using `dTrajObs`
        # and assign to a variable `logLikelihood`

    logPosterior <- # INSERT HERE: calulate the log-posterior using the
        # log-prior and log-likelihood

    return(logPosterior)

}

If you run into any problems, have a look at our solution. Otherwise, return to the practical.

 

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.