
## com213a of october 2025
#  based in nils Abel Envelopes stuff from march 2024,
#  apparently

#  here for stk4021 only the Baysian parts
#  here i use flat priors for both a and N;
#  can play with e.g. 1/N prior for N 

abel <- c(280,304,308,310,328)
nn <- length(abel) 
Un <- min(abel)
Vn <- max(abel)
Znobs <- Vn - Un # 48 

Nval <- seq(Znobs,200,by=1) # i am flexible here 

## then five more data points, in the course of 2009 to 2022: 

abel2 <- c(280,304,308,310,328, 285,314,317,327,334)
nn2 <- length(abel2) 
Un2 <- min(abel2)
Vn2 <- max(abel2)
Zn2obs <- Vn2 - Un2 # 54, just a bit bigger than Znobs = 48 


## ok then: Bayes, with flat prior on 1, 2, 3, ... for a
#  and flat prior on N, in a + 1, ..., a + N,
#  for kiosk story about Abel envelopes

#  after 2008, n = 5 datapoints 

qval <- (Nval - Znobs)*(Vn > Nval) + (Un - 1)*(Vn <= Nval)
logpostval0 <- log(qval) - log(choose(Nval,nn))
postval0 <- exp(logpostval0 - max(logpostval0))
postval <- postval0 / sum(postval0)

plot(Nval, postval, type="o")

#  after 2022, n = 10 datapoints 

q2val <- (Nval - Zn2obs)*(Vn2 > Nval) + (Un2 - 1)*(Vn2 <= Nval)
index2 <- (1:length(Nval))[Nval < Zn2obs]
q2val[index2] <- 0*(1:length(index2))

logpost2val0 <- log(q2val) - log(choose(Nval,nn2))
post2val0 <- exp(logpost2val0 - max(logpost2val0))
post2val <- post2val0 / sum(post2val0)

plot(Nval, post2val, type="o")

##

cdfbayes <- cumsum(postval)
cdf2bayes <- cumsum(post2val) 

matplot(Nval,
   cbind(cdfbayes,cdf2bayes), type="l",lwd=3)

#  right: Bayes, 2008 and 2022: 
#  making Abel figure, with cdf: 

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

matplot(Nval,cbind(cdfbayes,cdf2bayes),type="l",lwd=3,
   xlab="no. of Abel 1929 FDC envelopes",
   ylab="Bayes cdf, after 2008, after 2022")

matlines(Nval,0*Nval,type="l",lty=3,lwd=3)
matlines(Nval,0.50+0*Nval,type="l",lty=3,lwd=3)
grid(lwd=3) 


#  making Abel figure, with point probabilities: 

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

plot(Nval, postval, type="o",lwd=3,ylim=c(0,max(post2val)),
   xlab="no. of Abel 1929 envelopes",
   ylab="Bayes distributions, rounds I and II")

matpoints(Nval, post2val,type="o",pch=1,lwd=3,col=2)
matlines(Nval,0*Nval,type="l",lwd=3,lty=3) 
grid(lwd=3) 

# reading off posterior medians from: 
cbind(Nval,cdfbayes,cdf2bayes)[1:40, ]

Nhatone1 <- sum(Nval*postval)
Nhatone2 <- Nval[postval == max(postval)]
Nhatone3 <- 75 # 

Nhattwo1 <- sum(Nval*post2val)
Nhattwo2 <- Nval[post2val == max(post2val)]
Nhattwo3 <- 65 # 

#                      mean  median  mode 
## after first five:   84.8   75     59 
## after ten numbers:  68.1   65     59    ja så sannelig unchanged mode 

## ok then let me also find credibility intervals:

lowerone <- max( Nval[cdfbayes <= 0.05] ) 
upperone <- max( Nval[cdfbayes <= 0.95] ) 
# from 52 to 151, with five envelopes

lowertwo <- max( Nval[cdf2bayes <= 0.05] ) 
uppertwo <- max( Nval[cdf2bayes <= 0.95] ) 
# from 55 to 90, after ten envelopes 