## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 7,
  fig.align = "center"
)

## ----setup--------------------------------------------------------------------
library(mixvlmc)
library(ggplot2)

## -----------------------------------------------------------------------------
pc <- powerconsumption[powerconsumption$week %in% 15:17, ]
elec <- cut(pc$active_power,
  breaks = c(0, 0.4, 8),
  labels = c("low", "high")
)
table(elec)

## -----------------------------------------------------------------------------
n_train <- sum(pc$week %in% 15:16)
elec_train <- elec[1:n_train]

## -----------------------------------------------------------------------------
elec_tune <- tune_vlmc(elec_train)
elec_tune

## -----------------------------------------------------------------------------
elec_vlmc <- as_vlmc(elec_tune)
draw(elec_vlmc)

## -----------------------------------------------------------------------------
elec_tune_r <- tune_vlmc(elec_train, max_depth = 4, backend = "R")
all.equal(elec_tune$results, elec_tune_r$results)

## -----------------------------------------------------------------------------
summary(elec_tune)

## -----------------------------------------------------------------------------
head(elec_tune$results)

## -----------------------------------------------------------------------------
best_row <- which.min(elec_tune$results$BIC)
elec_tune$results[best_row, ]

## ----fig.height=4, fig.alt="Line plot of the BIC against the cut off in native scale, on a logarithmic axis, for the models considered by tune_vlmc() on the binary electricity consumption series. The BIC decreases quickly when the cut off increases from its initial value, remains close to its minimum over a range of intermediate cut offs and then increases sharply for the largest cut offs, which give the simplest models."----
plot(elec_tune, cutoff = "native", log = "x")

## ----fig.height=5, fig.alt="Five panels showing the AIC, the BIC, the number of contexts, the depth and the log likelihood of the models considered by tune_vlmc() against the cut off in quantile scale. The number of contexts, the depth and the log likelihood increase with the cut off in quantile scale, that is with the complexity of the models. Both criteria are very high for the smallest cut offs, drop sharply and are minimal for small values of the cut off, the BIC increasing more than the AIC for larger cut offs."----
print(autoplot(elec_tune))

## -----------------------------------------------------------------------------
elec_tune_all <- tune_vlmc(elec_train, save = "all")
length(elec_tune_all$saved_models$all)
nrow(elec_tune_all$results)
aic_row <- which.min(elec_tune_all$results$AIC)
if (aic_row == 1) {
  elec_aic <- elec_tune_all$saved_models$initial
} else {
  elec_aic <- elec_tune_all$saved_models$all[[aic_row - 1]]
}
elec_aic

## -----------------------------------------------------------------------------
context_set <- function(model) {
  ctxs <- contexts(model, sequence = TRUE)$context
  sort(vapply(ctxs, paste, character(1), collapse = ", "))
}
elec_tune_aic <- tune_vlmc(elec_train, criterion = "AIC")
identical(context_set(elec_aic), context_set(as_vlmc(elec_tune_aic)))

## -----------------------------------------------------------------------------
elec_tune_all$results$depth[1]
min(elec_tune_all$results$AIC)
elec_tune_aic$results$depth[1]
min(elec_tune_aic$results$AIC)

## -----------------------------------------------------------------------------
elec_tune_init <- tune_vlmc(elec_train, save = "initial")
elec_aic_2 <- prune(elec_tune_init$saved_models$initial,
  cutoff = elec_tune_init$results$cutoff[aic_row]
)
all.equal(elec_aic, elec_aic_2)

## -----------------------------------------------------------------------------
nb_states <- length(states(elec_vlmc))
all.equal(
  elec_tune$results$alpha,
  pchisq(2 * elec_tune$results$cutoff, df = nb_states - 1, lower.tail = FALSE)
)

## -----------------------------------------------------------------------------
cutoff(elec_vlmc, scale = "native")

## -----------------------------------------------------------------------------
cutoff(elec_vlmc, scale = "native", raw = TRUE)

## -----------------------------------------------------------------------------
elec_simpler <- prune(elec_vlmc,
  cutoff = cutoff(elec_vlmc, scale = "native")[1]
)
elec_simpler

## -----------------------------------------------------------------------------
init_results <- elec_tune_init$results
short_rows <- which(init_results$depth <= 3)
short_row <- short_rows[which.min(init_results$BIC[short_rows])]
elec_short <- prune(elec_tune_init$saved_models$initial,
  cutoff = init_results$cutoff[short_row]
)
draw(elec_short)

## -----------------------------------------------------------------------------
BIC(elec_vlmc)
min(elec_tune$results$BIC)

## -----------------------------------------------------------------------------
elec_ll <- loglikelihood(elec_vlmc,
  newdata = elec_train,
  ignore = elec_tune$results$depth[1]
)
elec_ll
BIC(elec_ll)

## -----------------------------------------------------------------------------
elec_tunes <- lapply(
  c("truncated", "specific", "extended"),
  function(ini) as_vlmc(tune_vlmc(elec_train, initial = ini))
)
data.frame(
  initial = c("truncated", "specific", "extended"),
  depth = sapply(elec_tunes, depth),
  nb_contexts = sapply(elec_tunes, context_number)
)

## -----------------------------------------------------------------------------
context_number(elec_vlmc) * (nb_states - 1)
sapply(
  c("truncated", "specific", "extended"),
  function(ini) attr(logLik(elec_vlmc, initial = ini), "df")
)

## -----------------------------------------------------------------------------
elec_models <- c(
  list(elec_tune_all$saved_models$initial),
  elec_tune_all$saved_models$all
)
holdout_ll <- sapply(
  elec_models,
  function(model) loglikelihood(model, newdata = elec, ignore = n_train)
)
elec_holdout <- cbind(
  elec_tune_all$results[c("cutoff", "depth", "nb_contexts", "AIC", "BIC")],
  holdout = holdout_ll
)
elec_holdout

## -----------------------------------------------------------------------------
holdout_row <- which.max(holdout_ll)
elec_holdout[c(aic_row, best_row, holdout_row), ]

## ----fig.height=4, fig.alt="Line plot with points of the hold-out log likelihood against the cut off in native scale, for the models with a finite hold-out log likelihood. The log likelihood increases with the cut off up to a maximum reached for a fairly simple model, and then decreases sharply for the simplest models."----
ggplot(
  elec_holdout[is.finite(elec_holdout$holdout), ],
  aes(x = cutoff, y = holdout)
) +
  geom_line() +
  geom_point() +
  scale_x_log10() +
  xlab("Cut off (native scale)") +
  ylab("Hold-out log likelihood")

## -----------------------------------------------------------------------------
period <- cut(pc$hour,
  breaks = c(-1, 6, 12, 18, 23),
  labels = c("night", "morning", "afternoon", "evening")
)
elec_cov <- data.frame(period = period)
elec_cov_train <- elec_cov[1:n_train, , drop = FALSE]

## -----------------------------------------------------------------------------
elec_cov_tune <- tune_covlmc(elec_train, elec_cov_train)
elec_cov_tune
elec_cov_tune$results

## -----------------------------------------------------------------------------
elec_covlmc <- as_covlmc(elec_cov_tune)
draw(elec_covlmc, model = "full")

## ----fig.height=5, fig.alt="Six panels showing the AIC, the BIC, the number of contexts, the covariate depth, the depth and the log likelihood of the models considered by tune_covlmc() against the cut off in quantile scale. The number of contexts, the depths and the log likelihood increase overall with the cut off. Both criteria are very high for the smallest cut offs and drop sharply; the BIC then increases slowly with the cut off while the AIC remains almost flat."----
print(autoplot(elec_cov_tune))

## -----------------------------------------------------------------------------
attr(logLik(elec_covlmc), "df")

## -----------------------------------------------------------------------------
min_sizes <- c(2, 5, 10, 20)
cov_models <- lapply(
  min_sizes,
  function(ms) as_covlmc(tune_covlmc(elec_train, elec_cov_train, min_size = ms))
)
common_ignore <- max(sapply(cov_models, depth))
data.frame(
  min_size = min_sizes,
  depth = sapply(cov_models, depth),
  nb_contexts = sapply(cov_models, context_number),
  cov_depth = sapply(cov_models, covariate_depth),
  BIC = sapply(cov_models, function(model) {
    BIC(loglikelihood(model,
      newdata = elec_train, newcov = elec_cov_train,
      ignore = common_ignore
    ))
  }),
  holdout = sapply(cov_models, function(model) {
    loglikelihood(model,
      newdata = elec, newcov = elec_cov,
      ignore = n_train
    )
  })
)

## -----------------------------------------------------------------------------
elec_cov_tune_all <- tune_covlmc(elec_train, elec_cov_train,
  save = "all", trimming = "partial"
)
cov_models_all <- c(
  list(elec_cov_tune_all$saved_models$initial),
  elec_cov_tune_all$saved_models$all
)
cov_columns <- c("alpha", "depth", "nb_contexts", "cov_depth", "BIC")
cov_holdout <- cbind(
  elec_cov_tune_all$results[cov_columns],
  holdout = sapply(cov_models_all, function(model) {
    loglikelihood(model, newdata = elec, newcov = elec_cov, ignore = n_train)
  })
)
cov_holdout

