
## com219a of november 2024
#  re kiosk exercise 5.51, we can do things with ML 

#  (1-p) pois(\theta) + p pois(c\theta) 

nn <- 250
theta0 <- 10
pp0 <- 0.10 
cc0 <- 2 

# generating a dataset:
set.seed(33) 
N <- rbinom(1,nn,pp0)
yy <- c(rpois(nn-N,theta0), rpois(N,cc0*theta0))

plot(yy)

## c = 2 known: estimate (p, \theta)

logL <- function(para)
{
pp <- para[1]
theta <- para[2]
#
aux <- (1-pp)*dpois(yy,theta) + pp*dpois(yy,cc0*theta)
sum(log(aux))
}

starthere <- c(0.15,15) 
logL(starthere)

minuslogL <- function(para)
{-logL(para)}

nils <- nlm(minuslogL,starthere,hessian=T)
ML <- nils$estimate
Jhat <- nils$hessian
sds <- sqrt(diag(solve(Jhat)))
showme <- cbind(ML,sds)
print(round(showme,4)) 
#          ML    sds
#[1,]  0.0906 0.0246 p 
#[2,] 10.2071 0.2477 theta

## then with (p,c,\theta) unknown

logL3 <- function(para)
{
pp <- para[1]
theta <- para[2]
cc <- para[3] 
#
aux <- (1-pp)*dpois(yy,theta) + pp*dpois(yy,cc*theta)
sum(log(aux))
}

starthere3 <- c(0.10,11,2) 
logL3(starthere3)

minuslogL3 <- function(para)
{-logL3(para)}

nils3 <- nlm(minuslogL3,starthere3,hessian=T)

ML3 <- nils3$estimate
Jhat3 <- nils3$hessian
sds3 <- sqrt(diag(solve(Jhat3)))
showme3 <- cbind(ML3,sds3)
print(round(showme3,4))

# ML3   sds3
#[1,]  0.0713 0.0208 p 
#[2,] 10.2120 0.2286 theta
#[3,]  2.2638 0.1587 c 
