
## com5a of february 2022,
#  bjornholt skiing days dataset, fitting perhaps as 
#  many as 3 * 2 = 6 models: constant, linear, quadratic trend,
#  then autocorrelation for each 
#  note: i use dataset going all the way to 2015 

snow <- matrix(scan("bjornholt_snow",skip=3),byrow=T,ncol=2)

year <- snow[ ,1] # from 1897 to 2015
xx <- snow[ ,2]   # number of skiings days 
nn <- length(year) # 102 different years, but big hole 1938 to 1954 

cbind(snow[1:20, ],snow[21:40, ],snow[41:60, ],
   snow[61:80, ],snow[81:100, ])

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

plot(year,xx,type="o",
    xlab="year",ylab="skiing days")

zz <- year-mean(year) 
zz2 <- zz^2 

## model 1: constant mean, independence
#  x = beta0 + sigma eps 
nils1 <- glm(xx ~ 1) 
res1 <- nils1$res
sigmahat1 <- sqrt( sum(res1^2)/(nn-0) ) 
ML1 <- c(nils1$coef, sigmahat1)

logL1max <- -nn*log(sigmahat1)-0.5*nn-0.5*nn*log(2*pi)
aic1 <- 2*length(ML1) - 2*logL1max
keep1 <- c(1,length(ML1),logL1max,aic1)

resid1 <- res1/sigmahat1
plot(year,resid1)
plot(density(resid1))
acf(resid1) # some autocorr, but not drastic 

## model 2: linear trend, independence
#  x = beta0 + beta1*zz + sigma eps 
nils2 <- glm(xx ~ zz) 
summary(nils2) # significant negative beta1

res2 <- nils2$res
sigmahat2 <- sqrt( sum(res2^2)/(nn-0) ) 
ML2 <- c(nils2$coef, sigmahat2)

logL2max <- -nn*log(sigmahat2)-0.5*nn-0.5*nn*log(2*pi)
aic2 <- 2*length(ML2) - 2*logL2max
keep2 <- c(2,length(ML2),logL2max,aic2)

resid2 <- res2/sigmahat2
plot(year,resid2)
plot(density(resid2))
acf(resid2) # some autocorr, but not drastic 

## model 3: quadratic trend, independence
#  x = beta0 + beta1*zz + beta2*zz^2 + sigma eps 

nils3 <- glm(xx ~ zz + zz2) 
summary(nils3) # significant negative beta1

res3 <- nils3$res
sigmahat3 <- sqrt( sum(res3^2)/(nn-0) ) 
ML3 <- c(nils3$coef, sigmahat3)

logL3max <- -nn*log(sigmahat3)-0.5*nn-0.5*nn*log(2*pi)
aic3 <- 2*length(ML3) - 2*logL3max
keep3 <- c(3,length(ML3),logL3max,aic3)

resid3 <- res3/sigmahat3
plot(year,resid3)
plot(density(resid3))
acf(resid3) # some autocorr, but not drastic 

2*(logL3max - logL2max) # very small: not worth it 

## model 4: linear trend, with autocorr
#  x_t = beta0 + beta1 zz + sigma eps, with rho
#  so x is multinormal, sigma^2 A(\rho) variance matrix

rhoval <- seq(-0.10,0.50,by=0.001) 
# i use 0.001 in the end, though it takes a bit of time,
# to have answers to 3 decimal places 
logL4profval <- 0*rhoval 

MLval <- 0*rhoval %*% t(1:3) 

A <- 0*(1:nn) %*% t(1:nn) 

for (rr in 1:length(rhoval))
{
rho <- rhoval[rr]
# 
for (i in 1:nn)
{for (j in 1:nn)
{A[i,j] <- rho^(abs(year[j]-year[i]))
}}
# 
logL4now <- function(para)
{
beta0 <- para[1]
beta1 <- para[2]
sigma <- para[3]
# 
Q <- t(xx-beta0-beta1*zz) %*% solve(A) %*% (xx-beta0-beta1*zz)
-nn*log(sigma)-0.5*log(det(A))-0.5*Q/sigma^2-0.5*nn*log(2*pi)
}
# 
minuslogL4now <- function(para)
{-logL4now(para)}
# 
nils4now <- nlm(minuslogL4now,ML2,hessian=T)
ML4now <- nils4now$estimate
MLval[rr, ] <- ML4now 
logL4profval[rr] <- logL4now(ML4now)
# 
print(c(rr,rho,logL4profval[rr]))
}

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

## creating snow_fig12.pdf 

rhohat <- rhoval[logL4profval == max(logL4profval)] # 0.208 
where0 <- (1:length(rhoval))[rhoval == 0]
where <- (1:length(rhoval))[logL4profval==max(logL4profval)]
ML4 <- c(MLval[where, ],rhohat)
logL4max <- max(logL4profval)
aic4 <- 2*length(ML4) - 2*logL4max
keep4 <- c(4,length(ML4),logL4max,aic4)

m2hatval <- ML4[1] + ML4[2]*zz

## creating snow_fig11.pdf 

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

plot(year,xx,
   xlab="year",ylab="skiing days at Bjoernholt")

# plot(year[1:41],xx[1:41],type="o",
#    xlim=c(1897,2012),ylim=range(xx),
#    xlab="year",ylab="skiing days at Bjoernholt") 

# matpoints(year[42:99],xx[42:99],type="p",pch=1)

matlines(year,m2hatval,type="l",lty=2,col=2,lwd=3)

## creating snow_fig12.pdf 

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

matplot(rhoval,logL4profval,type="l",
   xlab="rho", ylab="loglik profile",lwd=3)

matlines(rhoval,logL2max + 0*rhoval,type="l",lty=2,col=2,lwd=3)

# matlines(0 + 0*aux,logL2max+aux,type="l")

rhohat <- rhoval[logL4profval == max(logL4profval)] # 0.208 
where0 <- (1:length(rhoval))[rhoval == 0]
where <- (1:length(rhoval))[logL4profval==max(logL4profval)]
ML4 <- c(MLval[where, ],rhohat)
logL4max <- max(logL4profval)
aic4 <- 2*length(ML4) - 2*logL4max
keep4 <- c(4,length(ML4),logL4max,aic4)

## confidence curve for \rho, for kiosk story: 
dev4val <- 2*(logL4max - logL4profval)
cc4val <- pchisq(dev4val,1) 

hereweare<- rhoval[cc4val <= 0.95]
print(range(hereweare))

# making snow_fig13.pdf : 

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

matplot(rhoval,cc4val,type="l",
   xlab="rho", ylab="confidence curve",lwd=3)

matlines(hereweare, 0.95 + 0*hereweare,type="l",lty=2,col=2,lwd=3)
matlines(rhoval,0*rhoval,type="l",lty=3,col=1,lwd=2)

range(rhoval[cc4val <= 0.95]) # 0.013 to 0.393, c.i. for rho

## now with dataset up to 2015, nn = 102 years in total: 

keep <- rbind(keep1,keep2,keep3,keep4)
print(round(keep,4))

# data to 2015, n = 102: 
#        model dim logLmax  aic 
# keep1    1    2 -519.4789 1042.958 too simple 
# keep2    2    3 -512.1674 1030.335 no 2
# keep3    3    4 -511.6392 1031.278 no 3 
# keep4    4    4 -509.9827 1027.966 no 1


# previous round, with n = data points, to 2012: 
# keep1    1    2 -505.3060 1014.612
# keep2    2    3 -499.2870 1004.574
# keep3    3    4 -499.2755 1006.551
# keep4    4    4 -496.0681 1000.136

Delta <- logL4max - logL2max    # 2.1846
pvalue <- 1 - pchisq(2*Delta,1) # 0.0366 small enough: significant 
