
## com205c of october 2025
#  estimating twelve \sigma_i
#  plant data, Quebec and Minnesota

data(CO2)                       # base R
library(dplyr)
plant_stats <- CO2 %>%
  group_by(Plant) %>%
  summarize(n = n(),
            mean_y = mean(uptake),
            var_y = var(uptake))
plant_stats

# Quebec and Minnesota 

# 1 Qn1       7   33.2  67.5 
# 2 Qn2       7   35.2 121.  
# 3 Qn3       7   37.6 107.  
# 4 Qc1       7   30.0  69.5 
# 5 Qc3       7   32.6 107.  
# 6 Qc2       7   32.7 129.  
# 7 Mn3       7   24.1  42.1 
# 8 Mn2       7   27.3  58.6 
# 9 Mn1       7   26.4  75.6 
#10 Mc2       7   12.1   4.78
#11 Mc3       7   17.3   9.30
#12 Mc1       7   18    17.0 

yy0 <- plant_stats[ ,3]

t(yy0) 

varr0 <- plant_stats[ ,4]
round(t(varr0),3)

xi <- c(33.229, 35.157, 37.614, 29.971, 32.586, 32.7,
   24.114, 27.343, 26.4, 12.143,  17.3, 18.000) 

varr <- c(67.482, 121.09, 107.121, 69.466, 106.525, 128.527,
   42.051, 58.566, 75.59, 4.783, 9.297, 16.963)

nn <- length(xi) 

sigma <- sqrt(varr)

plants <- cbind(round(xi,3),round(sigma,3))

#      xi     sigma 
#       [,1]   [,2]
# [1,] 33.229  8.215
# [2,] 35.157 11.004
# [3,] 37.614 10.350
# [4,] 29.971  8.335
# [5,] 32.586 10.321
# [6,] 32.700 11.337
# [7,] 24.114  6.485
# [8,] 27.343  7.653
# [9,] 26.400  8.694
#[10,] 12.143  2.187
#[11,] 17.300  3.049
#[12,] 18.000  4.119


n0 <- 7 # datapoints per group 
mm <- n0 - 1 # df 

yy <- sigma^2 

logL <- function(para)
{
a <- para[1]
b <- para[2]
check <- 1*(a > 0)*(b > 0)

aux <- lgamma(a+0.5*mm)-lgamma(a) + a*log(b) - (a+0.5*mm)*log(b+0.5*mm*yy)
sum(aux)
}

logL(c(6,333))

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

nils <- nlm(minuslogL,c(6,333),hessian=T)
ML <- nils$estimate
Jhat <- nils$hessian
se <- sqrt(diag(solve(Jhat)))

print( round(cbind(ML,se),4) )
ahat <- ML[1]
bhat <- ML[2]

cov2cor( solve(Jhat) ) # unpleasant high correlation \hat a, \hat b 

# ML       se
# [1,]   6.6369  14.8724
# [2,] 385.9477 978.3532 very big b 


thetahat <- 1/yy
thetaeb <- (ahat + 0.5*mm) / (bhat + 0.5*mm*yy) # estimating theta = 1/sigma^2 

matplot(1:nn,cbind(thetahat,thetaeb),type="l")

sigmahat <- sqrt(yy)
sigmaeb <- 1/thetaeb^0.5

matplot(1:nn,cbind(sigmahat,sigmaeb),type="l",lwd=3,
   xlab="twelve plants", ylab="estimating sigma",
   lty=c(2,1),col=c(2,1))


logprior <- function(ab)
{
a <- ab[1]
b <- ab[2]
check <- 1*(a > 0)*(b > 0)
ifelse(check==1, -log(a) - log(b),-100)
# can do flat prior too: 
# ifelse(check==1, 1,-100)
# can do a more demanding prior, 1/a^3 1/b^3
# ifelse(check==1, -2*log(a) - 2*log(b),-100)
}

logprior(c(1,2))
logprior(c(1,-2))

set.seed(123) 

sim <- 1*10^5
mcmc <- 0*(1:sim) %*% t(1:2) 

uu <- runif(sim)
pracc <- 0*(1:sim)
ok <- 0*(1:sim)
eps1 <- rnorm(sim)
eps2 <- rnorm(sim) 

mcmc[1, ] <- c(ahat,bhat) 

d1 <- 0.40
d2 <- 3.50 

d1 <- 0.50 * se[1] # 0.10
d2 <- 0.50 * se[2] # 0.50

for (ss in 2:sim)
{
old <- mcmc[ss-1, ]
prop <- old + c(d1*eps1[ss],d2*eps2[ss])
#
check1 <- 1*(prop[1] > 0)*(prop[2]> 0)
check2 <- 1*(prop[1] < 100)*(prop[2] < 10000)
check <- check1*check2 
# 
oi1 <- ifelse(check==1, logprior(prop)-logprior(old), -100)
oi2 <- ifelse(check==1, logL(prop)-logL(old), -100)
pracc[ss] <- min(c(1,exp(oi1+oi2)))
ok[ss] <- 1*(uu[ss] <= pracc[ss])
mcmc[ss, ] <- (1-ok[ss])*old + ok[ss]*prop
}

plot(mcmc)

asim <- mcmc[ ,1]
bsim <- mcmc[ ,2]

plot(asim)
plot(bsim)

cor(asim,bsim) # 0.975, very high, but that's ok 

acf(asim)
acf(bsim) 

acf(asim, plot = F) # 0.993 ... 
acf(bsim, plot = F) # 0.993 ...

thetasim <- 0*(1:sim) %*% t(1:nn) 

for (ss in 1:sim)
{ thetasim[ss, ] <- rgamma(nn,asim[ss]+0.5*mm,bsim[ss]+0.5*mm*yy) }

B05 <- 0*(1:nn)
B50 <- 0*(1:nn)
B95 <- 0*(1:nn) 

for (i in 1:nn)
{
B05[i] <- quantile(thetasim[ ,i],0.05)
B50[i] <- quantile(thetasim[ ,i],0.50)
B95[i] <- quantile(thetasim[ ,i],0.95)
}

# for theta = 1/sigma^2 
matplot(1:nn,cbind(B05,B50,B95),type="l")

B05sigma <- 1/B95^0.50
B50sigma <- 1/B50^0.50
B95sigma <- 1/B05^0.50

## can be a good plot: 
#  making oblig_plants.ps : for sim = 10^5 


aux <- seq(0,1,by=0.10) 

xathere <- c(1,2,3, 4,5,6, 7,8,9, 10,11,12)

xlabelshere <- c(
   "Anderlecht","Beerst","Crehen",
   "Dinant","Erpe","Floreffe",
   "Ghent","Havelange","Ixelles",
   "Jemappes","Knokke","Leuven")

xlabelshere <- c(
   "Qn1", "Qn2", "Qn3",
   "Qc1", "Qc2", "Qc3",
   "Mn1", "Mn2", "Mn3",
   "Mc1", "Mc2", "Mc3")
   
par(bty="l")
par(cex.lab=1.4142) 

plot(1:nn,sigma,type="o",pch=1,lwd=4,lty=3,
   ylim=c(2,max(B95sigma)),,xlab=" " ,ylab="sigma",
   xaxt="n")
grid(lwd=4)    

matlines(1:nn,cbind(B05sigma, B50sigma, B95sigma),type="l",lwd=4,
   lty=c(2,1,2),col=c(2,1,2),ylim=c(2,13.5))

for (i in 1:nn)
{
matlines(i+0*aux, B05sigma[i] + aux*(B95sigma[i]-B05sigma[i]),
   type="l",lwd=4,lty=3,col=4)
}

matlines(1:nn,0*(1:nn) + mean(sigma),type="l",lwd=4,lty=2,col=3)

axis(1, at=xathere, labels=xlabelshere, las=2)

# matlines(1:nn,sigma,type="l",pch=1,lwd=3,lty=3)
# matlines(1:nn,sigmaeb,type="l",lwd=3,lty=1,col=4)

plot(sigma,sigmaeb)

plot(sigmaeb, B50sigma)

plot(sigmaeb / B50sigma)

well <- cbind(yy,sigmaeb,B05sigma,B50sigma,B95sigma,sigmaeb)
round(well,3)

sdsim <- sqrt(asim)/bsim

# the standard deviation is indeed quite close to zero:
# read the Sims Story in the Nils-Emil
# cooler prior to use (another time):
# 0.5 * (all \sigma_j equal) + 0.5 * gamma(a,b) 

# hist(sdsim,breaks=40)
