Skip to content

Commit f5d1fba

Browse files
committed
all in one place
1 parent 3295ac4 commit f5d1fba

File tree

1 file changed

+86
-1
lines changed

1 file changed

+86
-1
lines changed

code/cauchy_bimodal.r

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,92 @@ hist(theta.draws, probability = TRUE,
9797
curve(c_posterior, lwd = 3, add = TRUE)
9898
lines(density(IS.draws), lwd = 3, lty = 2, col = 2)
9999

100+
101+
############ Parallel tempering
102+
103+
U = function(gam, x)
104+
{
105+
- gam * c_logposterior_kernel(x)
106+
}
107+
108+
curried = function(gam)
109+
{
110+
message(paste("Returning a function for gamma =", gam))
111+
function(x)
112+
U(gam, x)
113+
}
114+
U4 = curried(4)
115+
116+
op = par(mfrow = c(2, 1))
117+
curve(U4(x), minT, maxT, main = "Potential function, U(x)")
118+
curve(exp(-U4(x)), minT, maxT, main = "Unnormalised density function, exp(-U(x))")
119+
par(op)
120+
121+
122+
chain = function(target, tune = 0.1, init = 1)
123+
{
124+
x = init
125+
xvec = numeric(iters)
126+
for (i in 1:iters) {
127+
can = x + rnorm(1, 0, tune)
128+
logA = target(x) - target(can)
129+
if (log(runif(1)) < logA)
130+
x = can
131+
xvec[i] = x
132+
}
133+
xvec
134+
}
135+
136+
temps = 2 ^ (0:3)
137+
iters = 1e5
138+
139+
mat = sapply(lapply(temps, curried), chain)
140+
colnames(mat) = paste("gamma=", temps, sep = "")
141+
142+
require(smfsb)
143+
mcmcSummary(mat, rows = length(temps))
144+
145+
146+
chains_coupled = function(pot = U,
147+
tune = 0.1,
148+
init = 1)
149+
{
150+
x = rep(init, length(temps))
151+
xmat = matrix(0, iters, length(temps))
152+
for (i in 1:iters) {
153+
can = x + rnorm(length(temps), 0, tune)
154+
logA = unlist(Map(pot, temps, x)) - unlist(Map(pot, temps, can))
155+
accept = (log(runif(length(temps))) < logA)
156+
x[accept] = can[accept]
157+
# now the coupling update
158+
swap = sample(1:length(temps), 2)
159+
logA = pot(temps[swap[1]], x[swap[1]]) + pot(temps[swap[2]], x[swap[2]]) -
160+
pot(temps[swap[1]], x[swap[2]]) - pot(temps[swap[2]], x[swap[1]])
161+
if (log(runif(1)) < logA)
162+
x[swap] = rev(x[swap])
163+
# end of the coupling update
164+
xmat[i, ] = x
165+
}
166+
colnames(xmat) = paste("gamma=", temps, sep = "")
167+
xmat
168+
}
169+
170+
mc3 <- chains_coupled(tune = 1)
171+
172+
mcmcSummary(mc3, rows = length(temps))
173+
174+
175+
par(mfrow = c(2, 2))
176+
for (k in 1:ncol(mc3)){
177+
hist(mc3[, k], probability = TRUE,
178+
xlim = c(minT, maxT),
179+
main = paste("gamma =", temps[k]),
180+
xlab = expression(theta))
181+
curve(c_posterior, lwd = 3, add = TRUE)
182+
}
183+
100184
##### Posterior mean estimates
101185
mean(theta.draws) ## MCMC (HMC)
102186
posterior.mean.quadrature ## quadrature
103-
m_is ## Importance sampling
187+
m_is ## Importance sampling
188+
colMeans(mc3)

0 commit comments

Comments
 (0)