#				
## Simulated data to test variance  - random treatment, 2 intervals (comparing at my covariance with (3.14))
#				

rm(list=ls())
library(MASS)

n.sim <- 1000
n.sample <- seq(250,1000,50)
source("../gestCov_txRand.R")
  
psi10 <- 1.6	
psi11 <- 0	
psi20 <- -3	
psi21 <- 2
psi22 <- 1	
psi23 <- 0	

bias.mat <- NULL

psi<-c(psi10,psi11,psi20,psi21,psi22,psi23)
results <- psi
alpha<-c(.5,.5)
get.vess <- 0
get.zipi <- 0
get.pur <- 0

se.sim <- NULL
mean.mySE <- NULL
median.mySE <- NULL

mean.mySEJR <- NULL
median.mySEJR <- NULL

for(psi23 in seq(-1,1,.1)) {
bias.vec <- NULL
for(n in n.sample) {
psi<-c(psi10,psi11,psi20,psi21,psi22,psi23)
results <- psi
   psi.est90 <- var.est90 <- NULL
   psi.est95 <- var.est95 <- NULL
   psi.est99 <- var.est99 <- NULL
   psi.estPUR <- var.estPUR <- NULL
   psi.estJR <- var.estJR <- NULL
   wrong.rule <- NULL
   for(j in 1:n.sim) {
if(j %in% seq(200,n.sim,200)) print(j)
      L1 <- rnorm(n,0,3)
      A1 <- rbinom(n,1,alpha[1])  
      L2 <- rnorm(n,.75,.5)
      A2 <- rbinom(n,1,alpha[2])  
      L <- cbind(L1,L2)
      A <- cbind(A1,A2)
      Y.opt <- rnorm(n,1,1) 
      Y <- Y.opt - abs(psi10 + psi11*L1)*(A1 - as.numeric(psi10 + psi11*L1>0))^2 - abs(psi20 + psi21*L2 + psi22*A1 + psi23*L2*A1)*(A2 - as.numeric(psi20 + psi21*L2 + psi22*A1 + psi23*L2*A1>0))^2      

      temp <- g_estCov.fcn(Y,L,A,return.U=F)
      psi.estJR <- cbind(psi.estJR,c(temp$psi.hat[2,1:2],temp$psi.hat[1,]))   
      var.estJR <- cbind(var.estJR,c(temp$psi.var[2,1:2],temp$psi.var[1,])) 
   }

   print(paste("n = ",n,sep=""))

   t0g <- apply(psi.estJR,1,sd)
   t1g <- apply(psi.estJR,1,mean)
   t1g.bias <- apply(psi.estJR-psi,1,mean)
   t1g.CV <- apply((psi.estJR-psi)/sqrt(var.estJR),1,mean)
   t2g <- apply(sqrt(var.estJR),1,mean) # calculated SE
   t3g <- apply(sqrt(var.estJR + (psi.estJR - psi)^2),1,mean)  # rMSE
#   t4g <- apply((psi.estJR - 1.96*sqrt(var.estJR) < psi) & (psi.estJR + 1.96*sqrt(var.estJR) > psi),1,sum)/n.sim*100 # Wald CI coverage
   t4g <- apply((psi.estJR - qt(.975,100)*sqrt(var.estJR) < psi) & (psi.estJR + qt(.975,100)*sqrt(var.estJR) > psi),1,sum)/n.sim*100 # Wald CI coverage

    results <- cbind(results,cbind(t1g,t2g,t3g,t4g))
#    results <- cbind(results,cbind(t1g,t1g.bias,t1g.CV,t0g,t2g,t3g,t4g))
    print(round(results,3))
    bias.vec <- c(bias.vec,t1g[1] - psi10)
}
bias.mat <- cbind(bias.mat,bias.vec)
}
bias.mat <- abs(bias.mat)

postscript("nobias_psi23a.eps")
filled.contour(seq(250,1000,50),seq(-1,1,.1),bias.mat,xlab="n",ylab=expression(psi[23]),col=rainbow(35),zlim=seq(0,.07,.0025))
dev.off()

