Skip to content

Commit

Permalink
Add generate method for VAR
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchelloharawild committed Sep 15, 2024
1 parent 856cf18 commit 933816c
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 1 deletion.
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,4 @@ Encoding: UTF-8
Language: en-GB
Roxygen: list(markdown = TRUE, roclets=c('rd', 'collate',
'namespace'))
RoxygenNote: 7.2.3
RoxygenNote: 7.3.1
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ S3method(generate,ETS)
S3method(generate,NNETAR)
S3method(generate,RW)
S3method(generate,TSLM)
S3method(generate,VAR)
S3method(generate,model_mean)
S3method(glance,AR)
S3method(glance,ARIMA)
Expand Down
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# fable (development version)

## New features

* Added generate() method for VAR models

# fable 0.3.4

Small patch to resolve issues in C++ R headers.
Expand Down
48 changes: 48 additions & 0 deletions R/var.R
Original file line number Diff line number Diff line change
Expand Up @@ -381,3 +381,51 @@ report.VAR <- function(object, ...) {
)
)
}

#' @inherit generate.ETS
#'
#' @export
generate.VAR <- function(x, new_data, specials, ...){
if (!".innov" %in% names(new_data)) {
new_data[[".innov"]] <- generate(distributional::dist_multivariate_normal(list(matrix(0, ncol = K)), x$fit$sigma2), nrow(new_data))[[1L]]
}

kr <- key_data(new_data)$.rows
h <- lengths(kr)
p <- x$spec$p
coef <- x$coef
K <- NCOL(coef)

# Get xreg
xreg <- specials$xreg[[1]]$xreg

# Generate paths
var_sim <- function(i) {
if (x$spec$constant) {
xreg <- cbind(constant = rep_len(1, length(i)), xreg)
}

.innov <- new_data$.innov[i,]

.sim <- matrix(NA, nrow = h, ncol = K)
y_lag <- matrix(0, nrow = p, ncol = K)
y_lag <- x$last_obs
for (i in seq_len(h)) {
if (is.null(xreg)) {
Z <- c(t(y_lag))
}
else {
Z <- c(t(y_lag), t(xreg[i, ]))
}
.sim[i, ] <- t(coef) %*% Z + .innov[i,]
y_lag <- rbind(.sim[i, , drop = FALSE], y_lag)[seq_len(p), , drop = FALSE]
}

.sim
}

.sim <- do.call(rbind, lapply(kr, var_sim))

new_data[colnames(coef)] <- split(.sim, col(.sim))
new_data
}
31 changes: 31 additions & 0 deletions man/generate.VAR.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 933816c

Please sign in to comment.