x = c(-5.00, -4.00, -3.00, -2.00, -1.00, 0.00, 1.00, 2.00, 3.00,  4.00, 5.00)
y = c(1.05,  3.20,  1.60,  3.05,  2.45, 2.90, 2.00, 2.20, 4.60,  4.00, 3.50)
par(mfrow=c(1,1))
plot(x,y)
fit0 = lm(y~1)
fit1 = lm(y~x)
anova(fit0,fit1)

n=5
m=2*n+1
M = 1000
beta0 = 1
betavec = seq(-1,1,by=0.05)
sig=1
alpha = 0.05
t0 = 8
counter=matrix(nrow=length(betavec),ncol=2)
y.pred = matrix(nrow=length(betavec),ncol=M)
y.pred2 = matrix(nrow=length(betavec),ncol=M)
sig.pred= matrix(nrow=length(betavec),ncol=M)
  
for(i in 1:length(betavec))
{  counter[i,1]=0;
   counter[i,2] =0;
  beta = betavec[i]
  for(j in 1:M)
  {
    y.sim = beta0+beta*x+rnorm(m,0,sig)
    fit = lm(y.sim~x)
    y.pred2[i,j]= fit$coef[1]+fit$coef[2]*t0
    if(summary(fit)$coef[2,4]<alpha)
      {
      y.pred[i,j] = fit$coef[1]+fit$coef[2]*t0
      counter[i,1]=counter[i,1]+1
      sig.pred[i,j]=sqrt(sum(fit$residuals^2)/(m-2))
      }
    else{
      y.pred[i,j] = mean(y.sim)
      counter[i,2]=counter[i,2]+1
      sig.pred[i,j] = sd(y.sim)
      }
    
  }
}


# a & c) just swap t0
yhat = apply(y.pred,1,mean)
ysd = apply(y.pred,1,sd)
ysd2 = apply(y.pred2,1,sd)
ssd = apply(sig.pred,1,mean)

#par(mfrow=c(1,1),mar=c(2,2,2,2))
par(mfrow=c(1,1))
matplot(betavec,counter,xlab="beta",ylab="Number of times selected",type="l")
legend("left",c("Linear","Constant"),lty=1,col=1:2)

par(mfrow=c(1,1))
plot(betavec,yhat,xlab="beta",ylab="yhat",type="l",main='mean theta')
abline(h=beta0,col=2)
lines(betavec,beta0+betavec*t0,col=3)
legend("topleft",c("Simulated","Constant","Linear"),lty=1,col=1:3)

plot(betavec,ysd,xlab="beta",ylab="sd(yhat)",type="l",ylim=c(0.,1.3),main='std theta')
abline(h=sig/sqrt(m),col=2)
lines(betavec,rep(sqrt(sig^2/m+t0^2*sig^2/(sum(x^2))),length(betavec)),col=3)
legend("topleft",c("Simulated","Constant","Linear"),lty=1,col=1:3)




#b  & d) just swap t0
# betavec[c(21, 25, 27 ,33)] 
par(mfrow=c(1,1))
plot(density(y.pred[21,],n=512,from=-8, to =8),type='l',col=1,main='p(theta)',xlim=c(-1,9))
lines(density(y.pred[25,],n=512,from=-8, to =8),col=2)
lines(density(y.pred[27,],n=512,from=-8, to =8),col=3)
lines(density(y.pred[33,],n=512,from=-8, to =8),col=4)
legend("topleft",c("beta=0.0","beta=0.2","beta=0.3","beta=0.6"),lty=1,col=1:4)



#b  & d) just swap t0
# betavec[c(21, 25, 27 ,33)] 
#par(mfrow=c(1,1))
#plot(density(y.pred2[21,],n=512,from=-8, to =8),type='l',col=1,main='p(theta)',xlim=c(-1,9))
#lines(density(y.pred2[25,],n=512,from=-8, to =8),col=2)
#lines(density(y.pred2[27,],n=512,from=-8, to =8),col=3)
#lines(density(y.pred2[33,],n=512,from=-8, to =8),col=4)
#legend("topleft",c("beta=0.0","beta=0.2","beta=0.3","beta=0.6"),lty=1,col=1:4)




