library(MASS)
library(ggm)
source("MCMC_Mallows.R")
set.seed(12345)

##########################################
## Define network structure and parameters, sigma = 0.1
##########################################
p=10
str=matrix(0, nrow=p, ncol=p)
str[1,c(4,5,6,7,9,10)]=str[2,c(6,9)]=str[3,c(4,7,9)]=str[4,c(7,9)]=str[5,c(7,8,10)]=
	str[6,10]=str[7,9]=str[8,c(9,10)]=str[9,10]=1
sgn=sign(matrix(runif(p*p,-1,1),nrow=p))
ref=list(m=rep(0.5,p), s=rep(0.1,p), W=round(str*sgn*matrix(runif(p*p,.25,1),nrow=p),2));
rownames(ref$W)=colnames(ref$W)=names(ref$s)=names(ref$m)=paste("N",1:p,sep="")
struct=ref$W!=0;
trueGBN = new("GBNetwork", WeightMatrix=ref$W, resMean=ref$m, resSigma=ref$s)

##########################################
## Generate and format complete single KO data with 10 wt
##########################################
x=rbind(simulGBN(10,ref$m,ref$s,ref$W),
  t(mapply(function(int) {simulGBN(1,ref$m,ref$s,ref$W,int=int,int_data=matrix(0,nrow=1))},
           int=1:p)));
int.nodes=rbind(matrix(0,nrow=10,ncol=p), diag(1,p))
data=dataFormat(x, int.nodes=int.nodes)

##########################################
## Initialize network (randomize order of variables, full estimation)
##########################################
mu = rep(0,p); Sigma = rep(1e-4,p); W = matrix(0, nrow=p, ncol=p)
W[upper.tri(W)] = 1
randomIndex <- sample(1:p, p)
rownames(W) = colnames(W) = names(mu) = names(Sigma) = paste("N",1:p,sep="")[randomIndex]
data = dataOrder(data, randomIndex)  
firstGBN = new("GBNetwork",WeightMatrix=W,resMean=mu,resSigma=Sigma)
firstGBN = GBNmle(firstGBN, data, nullModel=FALSE, shortcut=FALSE)$GBN

##########################################
## Run MCMC-Mallows
## 100 iterations, no burn-in, no thinning
##########################################
run = MCMC.GBN(data=data, firstGBN=firstGBN, nbSimulation=100, burnIn=0, seq=1, verbose=FALSE,
      type="MallowsProposal", alpha=0.8)
## Calculate causal effects
causal = causalEffects(run$full.run)
## Posterior means of direct and total causal effects
direct.causal <- matrix(apply(causal$alpha, 2, mean), nrow=p)
total.causal <- matrix(apply(causal$beta, 2, mean), nrow=p)
colnames(direct.causal) <- colnames(total.causal) <- rownames(direct.causal) <- 
	rownames(total.causal) <- colnames(run$full.run[[1]]@WeightMatrix)
