
# file "Rmwg" -- Metropolis-within-Gibbs algorithm, systematic 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 = 1000  # run length
B = 100  # amount of burn-in
X = c(0,0)  # initial Markov chain value (dim=2)
sigma = 1  # proposal scaling
x1list = x2list = NULL
hlist = NULL  # for keeping track of h function values

for (i in 1:M) {
  for (coord in 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 = c(x1list, X[1])
    x2list = c(x2list, X[2])
  }
  if (i>B)
    hlist = c(hlist, h(X))  # keep h value if burn-in over
}

cat("mean of h is about", mean(hlist), "\n")

# OTHER POSSIBLE COMMANDS:

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

se1 =  sd(hlist) / sqrt(length(hlist))
cat("iid standard error is about", se1, "\n")

# s = 0; for (i in 2:M) s = s + x1list[i]*x1list[i-1]
# cat("lag-one covariance of X[1] equals", s/(M-1) - (mean(x1list)^2), "\n")

# acf(x1list)

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

