#Exercise 4.1
y = c(-2,-1,0,1.5,2.5)
#y = c(43,44,45,46,46.5,47.5)    #Alternative dataset

logL = function(theta,y)
{
  -sum(log(1+(y-theta)^2))
}

minuslogL = function(theta,y)
{
  sum(log(1+(y-theta)^2))
}

dlogL = function(theta,y)
{
  sum(2*(y-theta)/(1+(y-theta)^2))
}

d2logL = function(theta,y)
{
  2*sum((1-(y-theta)^2)/(1+(y-theta)^2)^2)
}

theta = seq(min(y),max(y),length=100)
l = rep(NA,length(theta))
for(i in 1:length(theta))
  l[i] = logL(theta[i],y)
plot(theta,l,type="l")

#Optimize by steepest gradient
diff = 1;eps=0.0001
theta = mean(y)
learn.rate = 0.1
show(c(theta,logL(theta,y)))
while(diff>eps)
{
  theta.new = theta + learn.rate*dlogL(theta,y)
  diff = abs(theta.new-theta)
  theta = theta.new
  show(c(theta,logL(theta,y)))
}

#Using direct optimizer
res = optim(mean(y),minuslogL,lower=min(y),upper=max(y),method="Brent",hessian=TRUE,y=y)

V = d2logL(res$par,y)
show(V)
V = res$hessian
show(V)

#Note: Using flat prior here, can use uniform on a given interval instead.
low = -4; high = 5
se = 1/sqrt(res$hessian[1,1])
low = res$par-4*se
high = res$par+4*se
low = 0;high=1
theta = seq(low,high,length=100)
l = rep(NA,length(theta))
for(i in 1:length(theta))
  l[i] = logL(theta[i],y)
L = exp(l)
L = L/diff(theta[1:2]*sum(L))
dd = dnorm(theta,res$par,1/sqrt(V))
dd = dd/diff(theta[1:2]*sum(dd))
matplot(cbind(theta,theta),cbind(L,dd),type="l",
        lwd=2,
        xlab="theta",ylab="density",lty=1)
legend("topright",c("True","Norm-approx"),lty=1,lwd=2,col=1:2)
