
# file "Rmwg2" -- Metropolis-within-Gibbs algorithm, random scan

g = function(x) {
    if ( (x[1]<0) || (x[1]>5) || (x[2]<0) || (x[2]>4) )
	return(0)
    else
	return( abs( cos(sqrt(x[1]*x[2])) ) )
}

h = function(x) { return( exp(x[1]) + x[2]^2 ) }

M = 4200  # run length (number of coordinate updates)
B = 200  # amount of burn-in
X = c(0,0)  # initial Markov chain value (dim=2)
sigma = 1  # proposal scaling
x1list = x2list = hlist = rep(0,M)

for (i in 1:M) {
    coord = floor( runif(1,1,3) )  # uniform on {1,2}
    Y = X
    Y[coord] = X[coord] + sigma * rnorm(1)  # propose in direction "coord"
    U = runif(1)  # for accept/reject
    alpha = g(Y) / g(X)  # for accept/reject
    if (U < alpha)
	X = Y  # accept proposal
    x1list[i] = X[1]
    x2list[i] = X[2]
    hlist[i] = h(X)
}

cat("mean of h is about", mean(hlist[(B+1):M]), "\n")

# OTHER POSSIBLE COMMANDS:

plot(x1list, x2list, type='l')
# plot(hlist, type='l')
# plot(x1list, type='l')
# plot(x2list, type='l')

se1 =  sd(hlist[(B+1):M]) / sqrt(M-B)
cat("iid standard error is about", se1, "\n")

varfact <- function(xxx) { 2 * sum(acf(xxx, plot=FALSE)$acf) - 1 }
cat("true standard error is about", se1 * sqrt( varfact(hlist[(B+1):M]) ), "\n")

