#Example Metropolis-Hastings 
#Target distribution 
f= function(x)
  {
    exp(-abs(x)^3/3)
}



N = 10000    # Number of iterations
x = rep(NA,N)
varProp=10^2 # variance of proposal

#Initial value
x =  0  # result should be independent of starting
acc = 0
for(i in 2:N)
{
  y = rnorm(1,0,varProp) # proposal
  if(abs(y)>3)
    R=0
  else
    R = f(y)*dnorm(x[i-1],0,varProp)/(f(x[i-1])*dnorm(y,0,varProp))         # 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)',ylim=c(-3 ,3))
hist(x,100,prob=T,ylim=c(0,0.5), xlim=c(-2.5, 2.5))
y = seq(-3,3,length=600)
#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(2,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)

