
## com158a of august 2025
#  this is for stk 4021 Ex 7.2,
#  poisson data with gamma prior 

# gamma prior (a,b): 
aa <- 0.1
bb <- 0.1 

# can try an overconfident prior, too sure of itself: 
# e.g. mean = 10, small variance: 
# aa <- 100*10.0
# bb <- 100 

yy <- c(6, 8, 7, 6, 7, 4, 11, 8, 6, 3)
# yy <- rpois(25,6.666)
nn <- length(yy) 

thetaval <- seq(1.5,12.0,by=0.01)

# the so-called silly prior, clashing with data, 
# which have to learn, step by step: 
# aa <- cc*theta0 
# bb <- cc 

# aa <- 0.50*50
# bb <- 0.50

# computing lots of p(\theta | y_1,...,y_j) 
curves <- 0*thetaval %*% t(1:nn)
curves2 <- 0*thetaval %*% t(1:nn)

for (j in 1:nn)
{ 
curves[ ,j] <- dgamma(thetaval,aa+cumsum(yy)[j],bb+j)
curves2[ ,j] <- pgamma(thetaval,aa+cumsum(yy)[j],bb+j)
}

## showing curves up to n0 = 6 

n0 <- 6 
colours <- sample(2:4,n0,replace=T)
linetypes <- sample(2:4,n0,replace=T) 
colours[1] <- 1 
colours[n0] <- 1 
linetypes[1] <- 2 
linetypes[n0] <- 1 

## making bayes_figure61.pdf : 

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

matplot(thetaval,curves[ ,1:n0],type="l",
   lty=linetypes,col=colours, lwd=3,
   xlab=expression(theta),ylab="posteriors, sequentially")

matlines(thetaval,dgamma(thetaval,aa,bb),type="l",lwd=3,lty=3)

## making bayes_figure62.pdf : 

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

matplot(thetaval,curves2[ ,1:n0],type="l",
   lty=linetypes,col=colours, lwd=3,
   xlab=expression(theta),ylab="cdf posteriors, sequentially")

matlines(thetaval,pgamma(thetaval,aa,bb),type="l",lwd=3,lty=3)
