This lab goes through an algorithmic technique known as “Approximate Bayesian Computing”. This tool uses simulation to do approximate Bayesian inference. While ABC is a good fit for some problems, it also suffers from some drawbacks (low efficiency, bias, difficulty in comparing simulations to observed data). Nevertheless, the basis rejection-ABC approach is a good example of an “embarrassingly parallel” problem, where computations can be dramatically sped up through parallelization.
Much of statistical inference is focused on the ‘likelihood’. For observed data \(\bf{y}\), and unknown parameter vector \(\boldsymbol{\theta}\), the likelihood describes the data generating distribution:
\(f({\bf{y}}|\boldsymbol{\theta})\)
For example, a normal likelihood for a sample of size \(n\) would look like:
\(f(\bf{y}|\mu, \sigma^2) = \prod_{i=1}^n \frac{1}{\sqrt{2\pi\sigma^2}}exp(\frac{(y_i - \mu)^2}{2\sigma^2})\)
Let’s define some “observed” data:
y <- c(3.6,-3.45,-1.12,-1.66,-0.21,1.81,1.38,-0.71,-1.8,-5.29,0.69,-4.25,2.5,1.99,-2.5,0.37,-2.31,0.94,-4.24,-3.04,-3.61,-5.63,-0.32,-2.76,-2.08,-1.41,3.56,-4.8,-2.09,0.91,-2.47,1.52,-0.58,-4.84,-1.12,-4.46,-6.18,-0.76,6.49,-0.14,-8.92,-2.23,0.81,-3.88,-6.54,-2.57,-2.16,1.75,1.42,0.16,3.6,-3.45,-1.12,-1.66,-0.21,1.81,1.38,-0.71,-1.8,-5.29,0.69,-4.25,2.5,1.99,-2.5,0.37,-2.31,0.94,-4.24,-3.04,-3.61,-5.63,-0.32,-2.76,-2.08,-1.41,3.56,-4.8,-2.09,0.91,-2.47,1.52,-0.58,-4.84,-1.12,-4.46,-6.18,-0.76,6.49,-0.14,-8.92,-2.23,0.81,-3.88,-6.54,-2.57,-2.16,1.75,1.42,0.16)
With these data and the likelihood, we can perform various tasks. For example, we commonly want to evaluate the likelihood (or the log-transformed likelihood) at a particular value of the parameters:
lk <- function(mu, sigmasq, y){
sum(dnorm(y, mu, sqrt(sigmasq), log = TRUE))
}
lk(mu=0,sigmasq = 1, y = y)
## [1] -619.5924
lk(mu=-1,sigmasq = 1, y = y)
## [1] -529.1324
lk(mu=-1,sigmasq = 2, y = y)
## [1] -345.1705
This kind of activity can be embedded in an optimization algorithm, trying to find maximum likelihood estimates. Another thing we can do with likelihoods is to generate data according to a particular set of parameters:
genData <- function(mu, sigmasq, n){
rnorm(n, mu, sqrt(sigmasq))
}
z <- genData(mu=-1,sigmasq=2,n=length(y))
plot(density(y, bw= 2), xlim = c(-15, 25), ylim = c(0,0.2),
main = "Simulated and Observed Data")
lines(density(z, bw=2), col = "red")
legend(x=7, y = 0.1, lty = c(1,1), col = c(1,2), legend = c("Observed y", "Simulated z"))
These tools can be used to condut “Bayesian” inference as well. In a Bayesian setting, we still have likelihoods, but we no longer treat the parameters needed to generate replicate data sets as simply “true but unknown constants” as in frequentist inferece. In frequentist inference, we want a good estimator of the true parameter, and the ability to estimate a confidence interval in such a way that \(100(1-\alpha)\%\) of the time, such a confidence interval will end up containing the true value.
In Bayesian statistics, we want the ability to describe our uncertainty about these parameters prior to observing the data - we do this with probability distributions, called prior distributions. For this Gaussian example, we might choose the following vague bivariate prior:
log.prior.dist <- function(mu, sigmasq){
dnorm(mu, 0, sd = 10, log = TRUE) + dgamma(sigmasq, 1,0.1, log = TRUE)
}
log.prior.dist(0,1)
## [1] -5.624109
log.prior.dist(0,10)
## [1] -6.524109
log.prior.dist(100,10)
## [1] -56.52411
This places independent prior distributions on \(\mu\) and \(\sigma^2\). As with all probability distributions, we can also simulate data from them:
generate_params_prior <- function(n){
cbind(rnorm(n,0,10), rgamma(n, 1,0.1))
}
# Illustrate distribution
sims <- generate_params_prior(100000)
hist(sims[,1], main = "Marginal Prior: mu", freq = FALSE)
hist(sims[,2], main = "Marginal Prior: sigmasq", freq = FALSE)
plot(sims[,1], sims[,2], xlab = "mu", ylab ="sigmasq", main = "Joint Prior Distribution", col = rgb(0,0,0,0.01), pch = 16)
Bayes’ rule states that:
\(f(\theta | y) = \frac{f(y|\theta)f(\theta)}{f(y)} \propto f(y|\theta)f(\theta)\)
A lot of Bayesian inferential techniques concern themselves with directly investigating this posterior distribution, or the kernal thereof (the unscaled version on the right of the previous expression). Approximate Bayesian Computing uses a “brute force” approach. In ABC, we simulate parameters from their prior distribution, use those parameters to simulate replicate data sets, and then keep only the parameters which generate replicate data which is close to our observed data. This filtering is the algorithmic equivalent of “conditioning” on the observed data.
For more information, refer to this paper, which introduces the idea and describes some more advanced ABC algorithms.
# function to generate replicate data sets from a parameter matrix
sim.x <- function(N, Theta){
out <- matrix(rnorm(N*nrow(Theta)), ncol = N)
out <- out * matrix(rep(Theta[,2], each = N), ncol = N,
byrow=TRUE)
out <- out + matrix(rep(Theta[,1], each = N), ncol = N,
byrow=TRUE)
return(out)
}
# function to generate parameters from prior
# Prior distribution for mean: N(0,10)
# Prior distribution for SD: gamma(1,0.1)
sim.theta <- function(Nsim){
cbind(rnorm(Nsim, sd = 10), rgamma(Nsim,1,0.1))
}
system.time({
# Run ABC rejection algorithm
priorVals <- sim.theta(1000000)
replicateData <- sim.x(N = length(y), priorVals)
diffs <- ((apply(replicateData,1,mean) - mean(y))^2 + (apply(replicateData,1,sd) - sd(y))^2)
keepers <- priorVals[diffs < 0.2,]}) -> timeSpent
cat(paste0(round(timeSpent[3]/nrow(keepers)*100, 3), " seconds elapsed per 100 samples."))
## 1.883 seconds elapsed per 100 samples.
## Results
hist(keepers[,1], main = "Approximate Marginal Posterior for Mu", xlab = "mu")
hist(keepers[,2], main = "Approximate Marginal Posterior for sigmasq", xlab = "sigmasq")
library(hexbin)
library(RColorBrewer)
rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
hexbinplot(keepers[,1]~keepers[,2], colramp = rf, main = "Approximate Joint Posterior", xlab = "sigmasq", ylab = "mu")
One setting in which ABC has some attractive features is for discrete spatiotemporal stochastic compartmental epidemic models. That’s a lot of words, but the essence is not too hard to unpack. “discrete spatiotemporal” indicates that these models use discrete time (t=1,2,3,…etc) and space (location 1,2,3, etc.), and “stochastic” indicates that they have a probabilistic component. “Compartmental epidemic model” just means that we’re modeling an infectious disease process, and we’re using a model which accounts for a number of distinct disease states to do so.
Consider the following SEIR model, which tracks individuals through susceptible-exposed-infectious-removed disease states (additional details available in this paper.
\(S_{0,j} \sim Poisson(\lambda_{S}(j))\)
\(E_{0,j} \sim Poisson(\lambda_E(j))\)
\(I_{0,j} \sim Poisson(\lambda_I(j))\)
\(R_{0,j} = N_j - I_0 - E_0 - S_0\)
For each time point, \(t\) and spatial location \(j\), we have the update:
\(S_{t+1,j} = S_{t,j} - E^*_{t,j}\)
\(E_{t+1,j} = E_{t,j} - I^*_{t,j} + E^*_{t,j}\)
\(I_{t+1,j} = I_{t,j} - R^*_{t,j} + I^*_{t,j}\)
\(R_{t+1,j} = R_{t,j} + R^*_{t,j}\)
where these transition compartments have the following binomial distributions:
\(E^*_{t,j} \sim binom(S_{t,j}, \pi^{(SE)}_{t,j})\)
\(I^*_{t,j} \sim binom(I_{t,j}, \pi^{(EI)})\)
\(R^*_{t,j} \sim binom(R_{t,j}, \pi^{(IR)})\)
and where:
\(\theta_{t,j} = \frac{I_{t,j}}{N_{j}}[e^{ {\bf X}\beta}]_{t,j}\)
\(\pi^{(SE)} = 1-exp(-\theta_{t,j}-\rho{\bf D}\theta_{t,.})\)
\(\pi^{(EI)} ~ beta(115, 885)\)
\(\pi^{(IR)} ~ beta(200, 800)\)
\(\beta \sim N(0,5)\)
\(\rho sim beta(1,5)\)
\(\lambda_S = (50000, 50000, 10000)\)
\(\lambda_E = (1,1,1)\)
\(\lambda_I = (1,1,1)\)
\(N = (51000, 51000, 11000)\)
in which \(\bf{D}\) is a contact rate matrix and \(\bf{X}\) is a covariate matrix of the appropriate dimension.
If that’s super confusing, don’t panic - I’m glossing over a lot of the details, and you don’t need a detailed understanding to complete the lab. In the code below is a function to simulate such data from the required inputs, and to simulate the required inputs from the specified priors. Note that to simulate such data, we don’t need to evaluate a complex density function like the likelihood (or more appropriately, the kernel of the posterior distribution). We can certainly construct one for this problem using the Markov dependence in time, but ABC does not require it.
simulate_prior <- function(n){
data.frame(beta0 = rnorm(n, sd = 5),
beta1 = rnorm(n, sd = 5),
rho = rbeta(n, 1, 5),
pi_EI = rbeta(n, 115,885),
pi_IR = rbeta(n, 200,800),
S01 = rpois(n,50000),
S02 = rpois(n,50000),
S03 = rpois(n,10000),
E01 = rpois(n,1),
E02 = rpois(n,1),
E03 = rpois(n,1),
I01 = rpois(n,1),
I02 = rpois(n,1),
I03 = rpois(n,1))
}
getX <- function(ntpts, nloc){
# Intercept and intervention term
X0 <- cbind(1, cumsum(1:ntpts > round(ntpts/2)))
X0[,2] <- X0[,2]/max(X0[,2])
X0[rep(1:ntpts, nloc),]
}
getD <- function(nloc){
# constant overall contact:
D <- 1-diag(nloc)
D/(nloc-1)
}
# Num time points = 150
simulate_data <- function(single_par, Nt = 150, N = c(51000, 51000, 11000)){
# Set up
X <- getX(Nt, length(N))
D <- getD(length(N))
S = E = I = R = Estar = Istar = Rstar = matrix(NA, nrow = 150 + 1, ncol = 3)
S[1,] = with(single_par, c(S01, S02, S03))
E[1,] = with(single_par, c(E01, E02, E03))
I[1,] = with(single_par, c(I01, I02, I03))
R[1,] = N - S[1,] - E[1,] - I[1,]
if (any(R[1,] < 0)){
# Bad starting value, return bad result
S[] <- Inf
E[] <- Inf
I[] <- Inf
R[] <- Inf
Estar[] <- Inf
Istar[] <- Inf
Rstar[] <- Inf
return(list(S=S[1:Nt,],
E=E[1:Nt,],
I=I[1:Nt,],
R=R[1:Nt,],
Estar=Estar[1:Nt,],
Istar=Istar[1:Nt,],
Rstar=Rstar[1:Nt,],
param = single_par))
}
beta = with(single_par, c(beta0, beta1))
rho = single_par$rho
theta_components = exp(matrix(X %*% beta, ncol = length(N)))
for (i in 1:Nt){
# Draw transition counts
theta <- I[i,]*theta_components[i,]/N
pi_SE = 1-exp(-theta - t(rho*(D %*% theta)))
Estar[i,] = rbinom(n = rep(1, ncol(S)), size = S[i,], prob = pi_SE)
Istar[i,] = rbinom(n = rep(1, ncol(S)), size = E[i,], prob = single_par$pi_EI)
Rstar[i,] = rbinom(n = rep(1, ncol(S)), size = I[i,], prob = single_par$pi_IR)
# Update compartments
S[i+1,] = S[i,] - Estar[i,]
E[i+1,] = E[i,] - Istar[i,] + Estar[i,]
I[i+1,] = I[i,] - Rstar[i,] + Istar[i,]
R[i+1,] = R[i,] + Rstar[i,]
}
list(S=S[1:Nt,],
E=E[1:Nt,],
I=I[1:Nt,],
R=R[1:Nt,],
Estar=Estar[1:Nt,],
Istar=Istar[1:Nt,],
Rstar=Rstar[1:Nt,],
param = single_par)
}
Now we’ve got just about everything we need to start doing ABC. Let’s generate a “true” data set to use for the analysis:
set.seed(123123)
true_data <- simulate_data(single_par = data.frame(beta0=-1, beta1=-2,
rho=0.1,
pi_EI=0.14,pi_IR=0.2,
S01=50000,S02=50000,S03=10000,
E01=0,E02=0,E03=5,
I01=0,I02=0,I03=0))
Usually in these cases, we only actually observe one of the compartments. Let’s assume we only have the ability to measure new infections, capture by the I_star matrix:
true_Istar <- true_data$Istar
Let’s plot what the data looks like:
col1 <- rgb(0.4980392, 0.7882353, 0.4980392,1)
col2 <- rgb(0.7450980, 0.6823529, 0.8313725,1)
col3 <- rgb(0.9921569, 0.7529412, 0.5254902,1)
plot(true_Istar[,1], type = "l", ylim = c(0,max(true_Istar)*1.1), col = col1, lwd = 2,
main = "New Infection Counts", xlab = "Time", ylab = "Count")
lines(true_Istar[,2], type = "l", col = col2, lwd = 2)
lines(true_Istar[,3], type = "l", col =col3, lwd = 2)
legend(x=10,y = 25, legend = paste0("Location ", 1:3), lwd=rep(3,3), col = c(col1,col2,col3))
To do ABC, we then simulate replicate data sets:
system.time({
pars <- simulate_prior(1000)
sim.list <- lapply(1:nrow(pars), function(i){if (i %% 100 ==0){print(i)};simulate_data(pars[i,])$Istar})
})
## [1] 100
## [1] 200
## [1] 300
## [1] 400
## [1] 500
## [1] 600
## [1] 700
## [1] 800
## [1] 900
## [1] 1000
## user system elapsed
## 5.16 0.00 5.16
e <- sqrt(sapply(sim.list, function(simI){sum((simI-true_Istar)^2)}))
As you might expect, our prior distribution describes epidemics which fall into very different groups: sometimes the pathogen dies out quickly, and other times it takes over the whole population. Here is the distribution of point-wise-euclidean distances produced by the previous simulation:
hist(e)
For us to have much confidence in the result, we ideally want pretty small values of this distance. How small can we go?
quantile(e, probs = seq(0,1,length = 20))
## 0% 5.263158% 10.52632% 15.78947% 21.05263% 26.31579%
## 93.30595 148.29026 148.29700 148.30037 148.30374 148.30374
## 31.57895% 36.84211% 42.10526% 47.36842% 52.63158% 57.89474%
## 148.31049 148.31723 7172.01262 11409.00244 12952.54486 14091.88736
## 63.15789% 68.42105% 73.68421% 78.94737% 84.21053% 89.47368%
## 14890.39618 15414.78464 15809.66160 16243.85238 16637.68468 17092.64682
## 94.73684% 100%
## 17575.99248 19735.19931
Let’s take a look at the parameter values which did best:
keepers <- pars[e <140,]
keepers$e <- e[e<140]
library(knitr)
kable(keepers)
| beta0 | beta1 | rho | pi_EI | pi_IR | S01 | S02 | S03 | E01 | E02 | E03 | I01 | I02 | I03 | e | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 231 | -1.0958791 | -8.470954 | 0.1949380 | 0.1178576 | 0.2038208 | 50104 | 49826 | 9983 | 0 | 2 | 2 | 0 | 0 | 1 | 129.03875 |
| 293 | -1.3413376 | -1.601856 | 0.1105552 | 0.1046866 | 0.2009281 | 49949 | 49769 | 10096 | 1 | 0 | 1 | 0 | 2 | 2 | 116.97863 |
| 369 | -1.2562058 | -3.745920 | 0.1628319 | 0.1116361 | 0.1959007 | 50131 | 49958 | 10078 | 1 | 1 | 1 | 2 | 2 | 1 | 126.39225 |
| 388 | -0.9549029 | -2.473328 | 0.0143246 | 0.1122765 | 0.1998005 | 49656 | 50252 | 9764 | 1 | 0 | 2 | 2 | 0 | 1 | 93.30595 |
| 608 | -1.3289452 | -4.545979 | 0.2551223 | 0.1161725 | 0.1908023 | 49700 | 49996 | 10072 | 1 | 1 | 3 | 2 | 0 | 2 | 125.86898 |
| 711 | -1.1088028 | -2.793200 | 0.1253838 | 0.0981469 | 0.2042411 | 50228 | 49707 | 9890 | 0 | 1 | 0 | 0 | 1 | 1 | 131.47243 |
| 848 | -0.9662832 | -1.082196 | 0.0474864 | 0.0965438 | 0.2069206 | 50071 | 50103 | 9968 | 0 | 0 | 0 | 0 | 0 | 3 | 122.45816 |
Let’s recall the true parameter:
kable(true_data$param)
| beta0 | beta1 | rho | pi_EI | pi_IR | S01 | S02 | S03 | E01 | E02 | E03 | I01 | I02 | I03 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| -1 | -2 | 0.1 | 0.14 | 0.2 | 50000 | 50000 | 10000 | 0 | 0 | 5 | 0 | 0 | 0 |
We can visualize the distribution we’re estimating relative to the true parameters. For example,
plot(density(keepers$beta0, bw = 1), main = "Density Estimate for Beta-0")
abline(v = true_data$param$beta0, col = "red")
plot(density(keepers$beta1, bw = 1), main = "Density Estimate for Beta-1")
abline(v = true_data$param$beta1, col = "red")
Looks like we’re doing pretty well, but there’s definitely room to improve. In particular, these distributions are very wide - there’s a lot of remaining uncertainty.
Generalize this code to run your simulations as jobs on Argon as shown in class. There are a couple different configurations you could choose, but your code should produce csv files corresponding to the “good” samples with small distance to the target epidemic. Generate at least 1000 total samples with distance to the true epidemic of less than or equal to 100.
Use the same “I_star” we generated above. You can save the result by running the code in this document, making sure to use the same random seed. Alternatively, you can use this code+seed to generate the same data for each node on Argon. Please submit your R code, HPC code, and final combined CSV file in a zip file uploaded to ICON.