library(MASS)
library(Matching)

set.seed(4338)

#Expit transform
expit<-function(x){return(1/(1+exp(-x)))}

n<-2000
p<-10

x.index<-1:p
al.select<-sample(0:1,size=p,rep=T)
be.select<-sample(0:1,size=p,rep=T)

#Confounders
confound.list<-x.index[al.select == 1 & be.select==1]

#Instruments
intrument.list<-x.index[al.select ==1 & be.select==0]

#Predictors of outcome only
outcomeonly.list<-x.index[al.select ==0  & be.select==1]

#Spurious variables
spurious.list<-x.index[al.select ==0  & be.select==0]

#Predictors of outcome
outcome.list<-sort(c(confound.list,outcomeonly.list))

#Predictors of exposure
treatment.list<-x.index[al.select ==1]

################################################

set.seed(43973)
#Generate alpha parameters (for treatment allocation)
al<-rnorm(p+1,0,2.0)

#Generate beta parameters (for outcome regression)
be<-rnorm(p+1,0,2.0)

theta<-2.0
sig.Y<-1

#Covariance matrix of predictors
Sig<-rWishart(1,p+1,diag(p)/(p+1))[,,1]


#Run replicates

nrep<-1000
ests.mat.match<-matrix(0,nrow=nrep,ncol=6)

for(irep in 1:nrep){
	#Predictors
	X<-mvrnorm(n,mu=rep(0,p),Sigma=Sig)

	#Data simulation
	Xmat<-cbind(rep(1,n),X)
	eta.Z<-Xmat %*% (c(1,al.select)*al)
	p.Z<-expit(eta.Z)
	Z<-rbinom(n,1,p.Z)
	eta.Y<-Z*theta+Xmat %*% (c(1,be.select)*be)
	
	Y<-eta.Y+rnorm(n)*sig.Y
	#boxplot(Y~Z)

	##########################################################

	#Matching using: all predictors

	p1<-glm(Z~X,family=binomial)
	ps.vals<-fitted(p1)

	rr  <- Match(Y=Y, Tr=Z, X=X, M=1, estimand='ATE');
	ests.mat.match[irep,1]<-rr$est

	rr  <- Match(Y=Y, Tr=Z, X=ps.vals, M=1, estimand='ATE');
	ests.mat.match[irep,2]<-rr$est

	rr  <- Match(Y=Y, Tr=Z, X=ps.vals, M=5, estimand='ATE');
	ests.mat.match[irep,3]<-rr$est
	
	rr  <- Match(Y=Y, Tr=Z, X=ps.vals, M=10, estimand='ATE');
	ests.mat.match[irep,4]<-rr$est

	p1<-glm(Z~X[,confound.list],family=binomial)
	ps.vals<-fitted(p1)

	rr  <- Match(Y=Y, Tr=Z, X=X[,confound.list], M=1, estimand='ATE');
	ests.mat.match[irep,5]<-rr$est

	rr  <- Match(Y=Y, Tr=Z, X=ps.vals, M=1, estimand='ATE');
	ests.mat.match[irep,6]<-rr$est


}

mse.vals<-n*apply((ests.mat.match-theta)^2,2,mean)
name.list<-c('X','M=1','M=5','M=10','Conf.X','Conf.PS')
boxplot(ests.mat.match,names=name.list,ylim=range(-2,6),main='Matching Estimates')
abline(h=theta,col='red')
text(1:ncol(ests.mat.match),rep(6,ncol(ests.mat.match)),format(mse.vals,digits=4))
dev.print(device = pdf, file='Match.pdf',width=11)

boxplot(Y~Z,names=c('Untreated','Treated')
mean(Y[Z==1])-mean(Y[Z==0])