
## com181 of a busy september 2025
#  re exam project stk4021 2014 British mining disaters per year 

yy <- c(
4, 5, 3, 1, 4, 4, 1, 5, 5, 3, 4, 2,
5, 2, 2, 3, 4, 2, 1, 3, 2, 2, 1, 1,
1, 1, 3, 0, 0, 1, 0, 1, 1, 0, 0, 3,
1, 0, 3, 2, 2, 0, 1, 1, 1, 0, 1, 0,
1, 0, 0)

nn <- length(yy) # 51 

par(bty="l")
par(cex.lab=1.4142)

plot(1:nn,yy+0.01*rnorm(nn),lwd=3,xlab="years",ylab="accidents")


tauval <- seq(1,nn-3)
logLprofval <- 0*tauval

hh <- function(x)
{ x*log(x) - x}

curve(hh,0,5) 

for (j in 1:length(tauval))
{
tau <- tauval[j]
yyL <- yy[1:tau]
yyR <- yy[(tau+1):nn]
thetahatL <- mean(yyL)
thetahatR <- mean(yyR)
#
logLprofval[j] <- tau*hh(thetahatL) + (nn-tau)*hh(thetahatR)
}

plot(tauval,logLprofval)

tauhat <- tauval[logLprofval == max(logLprofval)] # 22

yyL <- yy[1:tauhat]
yyR <- yy[(tauhat+1):nn]
thetahatL <- mean(yyL) # 3.045
thetahatR <- mean(yyR) # 0.896

## then Bayes:

#  \pi(\tau\midd\data) \propto \pi_0(\tau) q_L q_R

post0val <- 0*tauval 
qLval <- 0*tauval
qRval <- 0*tauval 

a <- 1
b <- 1 

for (j in 1:length(tauval))
{
tau <- tauval[j]
# 
yyL <- yy[1:tau]
yyR <- yy[(tau+1):nn]
meanL <- mean(yyL)
meanR <- mean(yyR)
#
hei1 <- lgamma(a+tau*meanL) - (a+tau*meanL)*log(b+tau)
hei2 <- lgamma(b+(nn-tau)*meanR) - (b+(nn-tau)*meanR)*log(b+nn-tau)
#
qL <- exp(hei1)
qR <- exp(hei2)
#
post0val[j] <- qL*qR
}

postval <- post0val / sum(post0val)

## nice plot 1:

par(bty="l")
par(cex.lab=1.4142) 

plot(tauval,postval,type="o",lwd=3,
   xlab="changepoint tau",ylab="posterior")

tauhatB <- tauval[postval == max(postval)] # also 22

sim <- 10^5
gammasim <- 0*(1:sim)

# tau from the posterior: 
tausim <- sample(tauval,sim,replace=T,prob=postval)

# for each tau, from the posterior, i simulate thetaL and thetaR
# and their ratio, now / before 

for (ss in 1:sim)
{
meanL <- mean(yy[1:tausim[ss]])
meanR <- mean(yy[(tausim[ss]+1):nn])
# 
thetaLsim <- rgamma(1,a+tausim[ss]*meanL,b+tausim[ss])
thetaRsim <- rgamma(1,b+(nn-tausim[ss])*meanR,b+(nn-tausim[ss]))
#
gammasim[ss] <- thetaRsim/thetaLsim
}

## nice plot 2:

par(bty="l")
par(cex.lab=1.4142) 

hist(gammasim,prob=T,breaks=40,main=" ",
   xlab="gamma = thetaR/thetaL",
   ylab="histogram")

round(quantile(gammasim,c(0.025,0.50,0.975)),3)

# 0.197 0.314 0.484 so very clearly below 1;
# good for miners and minors
