## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(MFF)
has_forecast <- requireNamespace("forecast", quietly = TRUE)
has_fable <- all(vapply(c("fable", "fabletools", "tsibble"), requireNamespace,
                        logical(1), quietly = TRUE))

## ----models, eval = has_forecast----------------------------------------------
y <- log(datasets::AirPassengers)
models <- list(
  ets_aaa = function(y, h) forecast::forecast(forecast::ets(y, model = "AAA"), h = h),
  airline = function(y, h) {
    forecast::forecast(forecast::Arima(y, order = c(0, 1, 1),
                                       seasonal = c(0, 1, 1)), h = h)
  },
  stl_ets = function(y, h) forecast::stlf(y, h = h),
  seasonal_naive = function(y, h) forecast::snaive(y, h = h)
)
pool <- rolling_train(y, models, horizon = 1, n_validation = 24, n_test = 24)
pool

## ----inspect, eval = has_forecast---------------------------------------------
info <- pool_info(pool)
range(info$metadata$validation_origins)
range(info$metadata$test_origins)

## ----fit, eval = has_forecast-------------------------------------------------
fit <- tune_mff(pool, clusters = 2:3, method = "fcm", m = c(1.5, 2),
                control = mff_control(seed = 21))
selected_configuration(fit)[c("clusters", "m")]
weights(fit)
evaluate(predict(fit, pool), test_observed(pool))

## ----series, eval = has_forecast, fig.width = 7, fig.height = 4---------------
plot(fit, type = "series", newdata = pool)

## ----fable, eval = has_fable--------------------------------------------------
ap <- tsibble::as_tsibble(datasets::AirPassengers)
stretched <- tsibble::stretch_tsibble(ap, .init = 108, .step = 1)
fable_fc <- fabletools::forecast(
  fabletools::model(stretched,
                    snaive = fable::SNAIVE(log(value)),
                    ets = fable::ETS(log(value) ~ error("A") + trend("A") +
                                       season("A")),
                    drift = fable::RW(log(value) ~ drift())),
  h = 1)
fable_pool <- as_mff_pool(fable_fc, data = ap, horizon = 1, n_test = 12)
fable_pool

