#Example Metropolis-Hastings
#Target distribution 
f= function(x)
  {
    exp(-abs(x)^3/3)
}

#1 Proposal distribution: Gaussian distribution centered at previous value

N = 10000    # Number of iterations
x = rep(NA,N)
stdProp=0.04 # std of proposal

#Initial value
x = rnorm(1)
acc = 0
for(i in 2:N)
{
  y = rnorm(1,x[i-1],stdProp) # proposal
  R = f(y)/f(x[i-1])          # acceptance ratio 
                              # note that the acceptance rate is min(1,R),
  if(runif(1)<R)              # The syntax her will give that since we allways accept if R>1 
  {
    x[i] = y
    acc = acc+1
  }
  else
   x[i] = x[i-1]
}


par(mfrow=c(3,1),mar=rep(2,4))
plot.ts(x[1:10000],type="s",main='Traceplot x (10000 first)')
hist(x,100,prob=T,ylim=c(0,0.5), xlim=c(-2.5, 2.5))
y = seq(min(x),max(x),length=100)
#Approximate normalizing constant numerically
k = sum(f(y)*(y[2]-y[1]))
lines(y,f(y)/k,col=2)
acf(x,main='Autocorrelation')

cat("Acceptance rate=",acc/(N-1),"\n")




#par(mfrow=c(3,1))
#plot(x[-1],x[-N],main='Lag one scatterplot')
#hist((x),100,prob=T,ylim=c(0, 0.5))
#lines(y,f(y)/k,col=2)
#hist(unique(x),100,prob=T,ylim=c(0, 0.5))
#lines(y,f(y)/k,col=2)

