library(mvtnorm)
x = as.matrix(read.table("../data/trivariatenormal.dat",header=T))
#Remove all rows with all data missing
num.mis = apply(is.na(x),1,sum)
x = x[num.mis<3,]

EM.trinormal = function(x)
{
  n = nrow(x)
  #Make table of missing values
  num.mis = apply(is.na(x),1,sum)
  #Initial values based on complete data
  x.compl = x[num.mis==0,]
  mu = colMeans(x.compl)
  Sigma = var(x.compl)

  #Make a matrix with estimates of all observations (equal to observed when given)
  y.hat = x
  #Array for conditional covariance matrix for all observations
  V = array(0,c(n,3,3))
  more = TRUE;eps=0.001
  while(more)
  {
    mu.new = rep(0,3)
    Sigma.new = matrix(0,nrow=3,ncol=3)
    for(i in 1:n)
     {
       #First find y.hat and V
       if(num.mis[i]>0)
        {
          ind = c(1:3)[!is.na(x[i,])]
          y.hat[i,] = mu[1:3]+Sigma[1:3,ind]%*%solve(Sigma[ind,ind])%*%matrix(x[i,ind]-mu[ind],ncol=1)
          V[i,,] = Sigma-Sigma[1:3,ind]%*%solve(Sigma[ind,ind])%*%Sigma[ind,1:3]
        }
      }
    #Then estimate
    mu.new = colMeans(y.hat)
    Sigma.new = matrix(0,3,3)
    for(i in 1:n)
      Sigma.new = Sigma.new + V[i,,]+(y.hat[i,]-mu)%o%(y.hat[i,]-mu)
    Sigma.new = Sigma.new/n
    more = (max(abs(mu-mu.new))>eps) | (max(abs(Sigma-Sigma.new))>eps)
    mu = mu.new
    Sigma = Sigma.new
  }
  list(mu=mu,Sigma=Sigma)
}

#Estimate based on all data
res = EM.trinormal(x)
mu.hat = res$mu
Sigma.hat = res$Sigma



#Non-parametric Bootstrapping
B = 100
n = nrow(x)
mu.boot = matrix(nrow=B,ncol=3)
for(b in 1:B)
{
  ind = sample(1:n,n,replace=T)
  x.new = x[ind,]
  res.new = EM.trinormal(x.new)
  mu.boot[b,] = res.new$mu
}

bias.mu = colMeans(mu.boot)-mu.hat
var.mu = apply(mu.boot,2,var)
ci.mu = apply(mu.boot,2,quantile,probs=c(0.025,0.975))
tab = rbind(mu.hat,bias.mu,var.mu,sqrt(var.mu),ci.mu)
colnames(tab) = c("mu[1]","mu[2]","mu[3]")
rownames(tab)[1:4] = c("Estimate","Bias","Variance","SE")
show("Non-parametric bootstrapping")
show(round(tab,3))



#Parametric Bootstrapping
B = 100
n = nrow(x)
mu.boot = matrix(nrow=B,ncol=3)
for(b in 1:B)
{
  x.new = rmvnorm(n,mu.hat,Sigma.hat)
  #Insert missing values
  x.new[is.na(x)] <- NA
  res.new = EM.trinormal(x.new)
  mu.boot[b,] = res.new$mu
}

bias.mu = colMeans(mu.boot)-mu.hat
var.mu = apply(mu.boot,2,var)
ci.mu = apply(mu.boot,2,quantile,probs=c(0.025,0.975))
tab = rbind(mu.hat,bias.mu,var.mu,sqrt(var.mu),ci.mu)
colnames(tab) = c("mu[1]","mu[2]","mu[3]")
rownames(tab)[1:4] = c("Estimate","Bias","Variance","SE")
show("Parametric bootstrapping")
show(round(tab,3))



