#Variational inference for mixture of Gaussians

######## 
## Get data
set.seed(40519051)
rm(list=ls())
K = 3
fac = 8  #  sets the separation
mu = c(-1,0,1)*fac
sig.mu = 2
tau.mu = 1/sig.mu^2  
sig2 = c(1,1,1)
n1 = 100
n = K*n1
x = rep(NA,n)

avgTrue=rep(0,K) # the avarage of each class in the data

for(k in 1:K)
{
  x[(k-1)*n1+1:n1] = rnorm(n1,mu[k],sqrt(sig2[k]))
  avgTrue[k]=mean(x[(k-1)*n1+1:n1])
}

plot(density(x))
hist(x,20)



####################################
#Variational inference
start_time <- Sys.time()
eps = 0.001

phi = matrix(1/K,nrow=n,ncol=K)
m = mu
s2 = rep(1,K)
more = TRUE
Elbo = 0


while(more)
{
  for(i in 1:n)
  {
    phi[i,] = exp(m*x[i]-0.5*s2-0.5*m^2)
    phi[i,] = phi[i,]/sum(phi[i,])
  }
 
 for(k in 1:K)
  {
    m[k] = sum(phi[,k]*x)/(tau.mu+sum(phi[,k]))
    s2[k] = 1/(tau.mu+sum(phi[,k]))
  }

  elbo = -0.5*tau.mu*sum(s2+m^2)-sum(rowSums(phi*log(phi)))+0.5*sum(log(s2))
  for(k in 1:K)
    elbo = elbo + sum(phi[,k]*(x*m[k]-0.5*s2[k]-0.5*m[k]^2))
  more = abs(tail(Elbo,n=1)-elbo)>eps

  Elbo = c(Elbo,elbo)
}
end_time <- Sys.time()
cat("Time for VI\n")
show(end_time - start_time)




######################################
#MCMC
mu.sim = c(0,1,2)
c.sim = rep(NA,n)
muM = NULL
M = 20000

start_time <- Sys.time()
for(it in 1:M)
{
  #Simulate c's
  for(i in 1:n)
  {
    p = dnorm(x[i],mu.sim,1)
    c.sim[i] = sample(1:K,1,prob=p)
  }
  #Simulate mu's
  for(k in 1:K)
  {
    n.k = sum(as.numeric(c.sim==k))
    mu.sim[k] = rnorm(1,sum(x[c.sim==k])/(tau.mu+n.k),1/sqrt(tau.mu+n.k))
  }
 # mu.sim = sort(mu.sim)
  muM = cbind(muM,sort(mu.sim))
}



end_time <- Sys.time()
show("Time MCMC")
show(end_time - start_time)

par(mfrow=c(1,1))
matplot(t(muM),type='l')


D = 100
muM = muM[,-c(1:D)]

mu.hat = rowMeans(muM)
p = cbind(dnorm(x,mu.hat[1],1),
          dnorm(x,mu.hat[2],1),
          dnorm(x,mu.hat[3],1))
for(i in 1:n)
  p[i,] = p[i,]/sum(p[i,])




###Plots
par(mfrow=c(2,2))
plot.ts(Elbo[-1])
for(k in 1:K)
{
  plot(p[,k],phi[,k])
  abline(c(0,1),col=2)
}
#pdf("../doc/VI_mix_Gauss_density_MH_100.pdf",height=5,width=15)

par(mfrow=c(3,1))
 d = density(muM[1,])
 matplot(cbind(d$x,d$x),
         cbind(d$y,dnorm(d$x,mu[1],sqrt(s2[1]))),
         xlab=expression(mu[1]),ylab="Density",type="l",lty=1,xlim=c(-4, 4))
 
 d = density(muM[2,])
 matplot(cbind(d$x,d$x),
         cbind(d$y,dnorm(d$x,mu[2],sqrt(s2[2]))),
         xlab=expression(mu[2]),ylab="Density",type="l",lty=1,xlim=c(-4, 4))
 
 d = density(muM[3,])
 matplot(cbind(d$x,d$x),
         cbind(d$y,dnorm(d$x,mu[3],sqrt(s2[3]))),
         xlab=expression(mu[3]),ylab="Density",type="l",lty=1,xlim=c(-4, 4))
#dev.off()
