From 5a3c610cb877dcf8182828cf216ced561884d819 Mon Sep 17 00:00:00 2001 From: mitchelloharawild Date: Wed, 27 Dec 2023 12:46:28 +1100 Subject: [PATCH 1/2] Added faster and better hfitted method for ETS model --- NAMESPACE | 1 + NEWS.md | 3 ++- R/ets.R | 20 ++++++++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index d3fd21c7..5cc77f53 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -81,6 +81,7 @@ S3method(getResponse,mforecast) S3method(getResponse,tbats) S3method(head,ts) S3method(hfitted,default) +S3method(hfitted,ets) S3method(logLik,ets) S3method(nobs,ets) S3method(plot,Arima) diff --git a/NEWS.md b/NEWS.md index 13fe3353..bf66bd03 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,7 @@ # forecast (development version) * hfitted now much faster for ARIMA models (danigiro, #949) - + * hfitted now much faster for ETS models, and produces fitted values from + initial states (#950) # forecast 8.21.1 * nnetar now allows p or P to be 0 diff --git a/R/ets.R b/R/ets.R index e2d256f1..bd48884a 100644 --- a/R/ets.R +++ b/R/ets.R @@ -1346,6 +1346,26 @@ fitted.ets <- function(object, h=1, ...) { } } +#' @export +hfitted.ets <- function(object, h=1, all_fits = FALSE, ...) { + n <- length(object$x) + out <- rep(NA_real_, n) + for(i in seq_len(n-h+1)) { + out[i+h-1] <- .C( + "etsforecast", + as.double(object$states[i, ]), + as.integer(object$m), + as.integer(switch(object$components[2], "N" = 0, "A" = 1, "M" = 2)), + as.integer(switch(object$components[3], "N" = 0, "A" = 1, "M" = 2)), + as.double(ifelse(object$components[4] == "FALSE", 1, object$par["phi"])), + as.integer(h), + as.double(numeric(h)), + PACKAGE = "forecast" + )[[7]][h] + } + out +} + #' @export logLik.ets <- function(object, ...) { structure(object$loglik, df = length(object$par) + 1, class = "logLik") From 7f2e837258b96306861787383b7c1b6fad5ea668 Mon Sep 17 00:00:00 2001 From: mitchelloharawild Date: Mon, 8 Jan 2024 15:50:18 +1100 Subject: [PATCH 2/2] Fix hfitted.ets generic consistency --- R/ets.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/ets.R b/R/ets.R index bd48884a..ebb0aee4 100644 --- a/R/ets.R +++ b/R/ets.R @@ -1347,7 +1347,7 @@ fitted.ets <- function(object, h=1, ...) { } #' @export -hfitted.ets <- function(object, h=1, all_fits = FALSE, ...) { +hfitted.ets <- function(object, h=1, ...) { n <- length(object$x) out <- rep(NA_real_, n) for(i in seq_len(n-h+1)) {