#Leapfrog with mixture of Gaussian
#########################################################
# Defining the prior model
pr = 0.3          # Probability of mode 1
mu = c(0,3)       # mean of modes 
sig = c(0.4,0.4)  # standardeviation of modes 

distr = function(x) # the target distribution
{
  pr*dnorm(x,mu[1],sig[1]) + (1-pr)*dnorm(x,mu[2],sig[2])
}

## PLotting target distribution
x = seq(-2,5,length=100)
plot(x,distr(x),type="l")
N = 105000
D =   5000 #(burn in)

###################################################
#Ordinary M-H
####################################################
X = rep(NA,N)    # storage of results
X[1] = rnorm(1)  # initialization 
sig.prop = 0.3   # standarddeviation of proposal

acc = 0          # counter to monitor acceptance

ptm <- proc.time() # timing
for(i in 2:N)
{
  x.prop = rnorm(1,X[i-1],sig.prop) # random walk proposal 
  R = distr(x.prop)/distr(X[i-1])   # M-H ratio
  if(runif(1)<R)                    # acceptance step
  {
    X[i] = x.prop
    acc = acc + 1
  }
  else
    X[i] = X[i-1]
}

show(proc.time() - ptm)
X.MH = X[-c(1:D)]
cat("Acceptance rate=",acc/(N-1),"\n")

##########################
#Leapfrog
####################################
U = function(x)     # potential energy
{
  -log(distr(x))
}

Hfunc = function(x,p) # total  energy
{
  U(x)+0.5*p^2/m
}

dU = function(x)   # derivative of potential energy function 
{
  d1 = dnorm(x,mu[1],sig[1],log=TRUE)
  d2 = dnorm(x,mu[2],sig[2],log=TRUE)
  dr = exp(d2-d1)
  r = (pr*(x-mu[1])/sig[1]^2 + (1-pr)*dr*(x-mu[2])/sig[2]^2)/(pr+(1-pr)*dr)
}

m = 1^2   ## variance in velocity (the augmented variable)

## check gradient is computed right
Nx=1000
x = seq(-2,5,length=Nx)
plot(0.5*(x[-1]+x[-Nx]),(U(x[-1])-U(x[-Nx]))/(x[-1]-x[-Nx]))
lines(x,dU(x),col=2)


## image leapfrog Show the joint distribution one move
Nx=500
Np=401
HM=matrix(nrow = Nx, ncol = Np)
x = seq(-3,6,length=Nx)
p = seq(-sqrt(m)*6,sqrt(m)*6,length=Np)
for(i in 1:Nx)
   for(j in 1:Np)
     HM[i,j]=Hfunc(x[i],p[j])
par(mfrow=c(1,1))
image(x,p,HM)   # joint ditribution image


L=100   # number of steps
xStore=rep(0,L+1)
pStore=rep(0,L+1)

eps=0.02;

x.prop =5
p.prop      = -2

xStore[1]=x.prop
pStore[1]=p.prop
points(x.prop,p.prop)

for(j in 1:L)
{ # Leap-frog
  p.half = p.prop - 0.5*eps*dU(x.prop)
  x.prop = x.prop + eps*p.half/m
  p.prop = p.half - 0.5*eps*dU(x.prop)
  xStore[j+1]=x.prop
  pStore[j+1]=p.prop
}
points(xStore[1],pStore[1])
lines(xStore,pStore)



## run leap frog
set.seed(231171)
L = 20
X = rep(NA,N)
X[1] = rnorm(1)
acc = 0
ptm <- proc.time()
for(i in 2:N)
{
  eps = runif(1,0.2,0.3)     # Random stepsize
  p.prop = rnorm(1,0,sqrt(m))
  H = Hfunc(X[i-1],p.prop) 
  x.prop = X[i-1]
  for(j in 1:L)
  {
    p.half = p.prop - 0.5*eps*dU(x.prop)
    x.prop = x.prop + eps*p.half/m
    p.prop = p.half - 0.5*eps*dU(x.prop)
  }
  H.prop = Hfunc(x.prop,p.prop)
  
  R = exp(H-H.prop)
  #show(c(X[i-1],x.prop,H,H.prop,R))
  if(runif(1)<R)
  {
    X[i] = x.prop
    acc = acc + 1
  }
  else
    X[i] = X[i-1]
}

X.HMC = X[-c(1:D)]
show(proc.time() - ptm)
cat("Acceptance rate=",acc/(N-1),"\n")

# plots
par(mfrow=c(1,1))
acf(X.MH,ylim=c(-0.1,1),lag.max=1000,col=3,main="X1")
par(new=T)
acf(X.HMC,ylim=c(-0.1,1),lag.max=1000,col=2,main="",lwd=2)
legend("topright",c("Random walk","Hamiltonian Monte Carlo"),lty=1,col=3:2)
par(mfrow=c(1,2))
hist(X.MH,30,prob=TRUE,ylim=c(0,1));lines(x,distr(x),col=2)
hist(X.HMC,30,prob=TRUE,ylim=c(0,1));lines(x,distr(x),col=2)

# plots
par(mfrow=c(2,1))
plot(X.MH,ylim=c(-2,6),col=3,main="Random walk",type='l')

plot(X.HMC,ylim=c(-2,6),col=2,main="Hamiltonian Monte Carlo",lwd=2,type='l')

