## -----------------------------------------------------------------------------
knitr::opts_chunk$set(
  dpi = 300,
  collapse = TRUE,
  comment = "#>"
)
library(season)
library(dplyr)
library(tibble)
library(stringr)
library(ggplot2)
library(flextable)
library(nimble) # for Bayesian models

## -----------------------------------------------------------------------------
ggplot(CVD, aes(x = yrmon, y = cvd)) +
  geom_line(colour = 'darkred', linewidth = 1.05) +
  labs(
    x = "Time",
    y = "Monthly number of CVD deaths"
  ) +
  theme_bw()

## -----------------------------------------------------------------------------
model1 <- monthglm(
  formula = cvd ~ 1,
  data = CVD,
  family = quasipoisson(),
  offsetpop = expression(pop / 100000),
  offsetmonth = TRUE,
  refmonth = 6
)
autoplot(model1, ylab = 'Rate ratio')

## -----------------------------------------------------------------------------
code_random_month <- nimbleCode({
  # Likelihood
  for (i in 1:N) {
    # loop through time
    cvd[i] ~ dpois(mu[i])
    log(mu[i]) <- log(offset[i]) + log(n_days_month[i]) + alpha + beta.c[month[i]]
  }
  # priors
  alpha ~ dnorm(0, sd = 100)
  for (k in 1:12) {
    beta[k] ~ dnorm(0, tau = tau.month)
    beta.c[k] <- beta[k] - mean.beta
  }
  mean.beta <- mean(beta[1:12])
  tau.month ~ dgamma(1, 1)
  # rescale to standard deviation
  sigma.month <- 1 / sqrt(tau.month) 
})

## -----------------------------------------------------------------------------
constants <- list(
  N = nrow(CVD),
  month = CVD$month,
  # scaled to per 100,000 people
  offset = CVD$pop / 100000,
  # scaled to per 30 days
  n_days_month = (CVD$ndaysmonth) / 30
)
data <- list(cvd = CVD$cvd)

## -----------------------------------------------------------------------------
inits <- list(
  tau.month = 1,
  alpha = log(mean(CVD$cvd / (CVD$pop / 100000))),
  beta = rep(0, 12)
)

## -----------------------------------------------------------------------------
# parameters to store
parms <- c('alpha', 'beta.c', 'sigma.month')
# define the model
model <- nimbleModel(
  code_random_month,
  data = data,
  inits = inits,
  constants = constants
)
# MCMC samples
thin <- 3
MCMC <- 1000
mcmc_random <- nimbleMCMC(
  model = model,
  inits = inits,
  monitors = parms,
  # times 2 for burn-in
  niter = MCMC * 2 * thin, 
  thin = thin,
  nchains = 2,
  nburnin = MCMC,
  summary = TRUE,
  # one seed per chain
  setSeed = c(1, 2), 
  WAIC = TRUE
)
# check chains for intercept - commented out because of file size for CRAN
#plot(mcmc_random$samples$chain1[, 1], type = 'l')
#lines(mcmc_random$samples$chain2[, 1], type = 'l', col = 'red')

## -----------------------------------------------------------------------------
# prepare estimates for plot
to_plot <- as.data.frame(mcmc_random$summary$all.chains) |>
  rownames_to_column() |>
  filter(str_detect(rowname, pattern = 'beta')) |>
  mutate(month = as.numeric(str_extract(rowname, pattern = '[1-9][0-2]?')))
# labels for x-axis
month.letter <- substr(month.abb, 1, 1)
# plot
colour <- 'darkorange2'
ggplot(
  to_plot,
  aes(
    x = month,
    y = exp(Mean),
    ymin = exp(`95%CI_low`),
    ymax = exp(`95%CI_upp`)
  )
) +
  geom_line(linewidth = 1.05, col = colour) +
  geom_errorbar(width = 0, linewidth = 1.05, col = colour) +
  geom_point(col = colour, size = 3) +
  geom_hline(lty = 2, yintercept = 1) +
  ylab('Rate ratio') +
  xlab(NULL) +
  scale_x_continuous(breaks = 1:12, labels = month.letter) +
  theme_bw() +
  theme(panel.grid.minor = element_blank())

## -----------------------------------------------------------------------------
neighbours <- toeplitz(c(NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA))
# link January and December
neighbours[1, 12] <- neighbours[12, 1] <- 1 
neighbours
adj <- createAdj(neighbours)

## -----------------------------------------------------------------------------
code_neighbour_month <- nimbleCode({
  # Likelihood
  for (i in 1:N) {
    # loop through time
    cvd[i] ~ dpois(mu[i])
    log(mu[i]) <- log(offset[i]) + log(n_days_month[i]) + alpha + beta[month[i]]
  }
  # priors
  alpha ~ dnorm(0, sd = 100)
  beta[1:12] ~ dcar_normal(
    adj[1:L],
    weights[1:L],
    num[1:12],
    tau.neighbours,
    zero_mean = 1
  )
  tau.month ~ dgamma(1, 1)
  tau.neighbours ~ dgamma(1, 1)
  # rescale to standard deviation
  sigma.month <- 1 / sqrt(tau.month) 
  sigma.neighbours <- 1 / sqrt(tau.neighbours)
})


## -----------------------------------------------------------------------------
constants <- list(
  N = nrow(CVD),
  L = length(adj$adj),
  adj = adj$adj,
  num = adj$num,
  weights = adj$weight,
  month = CVD$month,
  # scaled to per 100,000 people
  offset = CVD$pop / 100000, 
  # scaled to per 30 days
  n_days_month = (CVD$ndaysmonth) / 30
) 


## -----------------------------------------------------------------------------
# parameters to store
parms <- c('alpha', 'beta', 'sigma.month', 'sigma.neighbours')

# define the model
model <- nimbleModel(
  code_neighbour_month,
  data = data,
  inits = inits,
  constants = constants
)

# MCMC samples
mcmc_neighbours <- nimbleMCMC(
  model = model,
  inits = inits,
  monitors = parms,
  # times 2 for burn-in
  niter = MCMC * 2 * thin, 
  thin = thin,
  nchains = 2,
  nburnin = MCMC,
  summary = TRUE,
  # one seed per chain
  setSeed = c(1, 2), 
  WAIC = TRUE
)
# check chains for intercept - commented out for file size
#plot(mcmc_neighbours$samples$chain1[, 1], type = 'l')
#lines(mcmc_neighbours$samples$chain2[, 1], type = 'l', col = 'red')


## -----------------------------------------------------------------------------
# prepare estimates for plot
to_plot <- as.data.frame(mcmc_neighbours$summary$all.chains) |>
  rownames_to_column() |>
  filter(str_detect(rowname, pattern = 'beta')) |>
  mutate(month = as.numeric(str_extract(rowname, pattern = '[1-9][0-2]?')))
# plot
colour <- 'darkseagreen3'
ggplot(
  to_plot,
  aes(
    x = month,
    y = exp(Mean),
    ymin = exp(`95%CI_low`),
    ymax = exp(`95%CI_upp`)
  )
) +
  geom_line(linewidth = 1.05, col = colour) +
  geom_errorbar(width = 0, linewidth = 1.05, col = colour) +
  geom_point(col = colour, size = 3) +
  geom_hline(lty = 2, yintercept = 1) +
  ylab('Rate ratio') +
  xlab(NULL) +
  scale_x_continuous(breaks = 1:12, labels = month.letter) +
  theme_bw() +
  theme(panel.grid.minor = element_blank())


## -----------------------------------------------------------------------------
waic1 <- data.frame(
  model = 'Random',
  parameters = mcmc_random$WAIC$pWAIC,
  WAIC = mcmc_random$WAIC$WAIC
)
waic2 <- data.frame(
  model = 'Neighbours',
  parameters = mcmc_neighbours$WAIC$pWAIC,
  WAIC = mcmc_neighbours$WAIC$WAIC
)
to_table <- bind_rows(waic1, waic2)
flextable(to_table) |>
  colformat_double(j = 2:3, digits = 1)


