-
Notifications
You must be signed in to change notification settings - Fork 36
/
MinT.R
340 lines (325 loc) · 11.5 KB
/
MinT.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
## Arguments
# x: Matrix of insample residuals for all time series in the hierarchy. Each column referring to one time series.
# Target matrix for shrinking towards a diagonal matrix
lowerD <- function(x)
{
n <- nrow(x)
return(diag(apply(x, 2, crossprod) / n))
}
## Arguments
# x: Matrix of insample residuals for all time series in the hierarchy. Each column referring to one time series.
# tar: Lower dimensional matrix.
# Shrinked covariance matrix - Schafer and strimmer approach
shrink.estim <- function(x, tar)
{
if (is.matrix(x) == TRUE && is.numeric(x) == FALSE)
stop("The data matrix must be numeric!", call. = FALSE)
p <- ncol(x)
n <- nrow(x)
covm <- crossprod(x) / n
corm <- cov2cor(covm)
xs <- scale(x, center = FALSE, scale = sqrt(diag(covm)))
v <- (1/(n * (n - 1))) * (crossprod(xs^2) - 1/n * (crossprod(xs))^2)
diag(v) <- 0
corapn <- cov2cor(tar)
d <- (corm - corapn)^2
lambda <- sum(v)/sum(d)
lambda <- max(min(lambda, 1), 0)
shrink.cov <- lambda * tar + (1 - lambda) * covm
return(list(shrink.cov, c("The shrinkage intensity lambda is:",
round(lambda, digits = 4))))
}
# MinT - Trace minimization approach
#' Trace minimization for hierarchical or grouped time series
#'
#' Using the method of Wickramasuriya et al. (2019), this function combines the
#' forecasts at all levels of a hierarchical or grouped time series. The
#' \code{\link{forecast.gts}} calls this function when the \code{MinT} method
#' is selected.
#'
#' @param fcasts Matrix of forecasts for all levels of a hierarchical or
#' grouped time series. Each row represents one forecast horizon and each
#' column represents one time series of aggregated or disaggregated forecasts.
#' @param nodes If the object class is hts, a list contains the number of child
#' nodes referring to hts.
#' @param groups If the object is gts, a gmatrix is required, which is the same
#' as groups in the function gts.
#' @param residual Matrix of insample residuals for all the aggregated and
#' disaggregated time series. The columns must be in the same order as
#' \code{fcasts}.
#' @param covariance Type of the covariance matrix to be used. Shrinking
#' towards a diagonal unequal variances (\code{"shr"}) or sample covariance matrix
#' (\code{"sam"}).
#' @param nonnegative Logical. Should the reconciled forecasts be non-negative?
#' @param algorithms Algorithm used to compute inverse of the matrices.
#' @param keep Return a gts object or the reconciled forecasts at the bottom
#' level.
#' @param parallel Logical. Import parallel package to allow parallel processing.
#' @param num.cores Numeric. Specify how many cores are going to be used.
#' @param control.nn A list of control parameters to be passed on to the
#' block principal pivoting algorithm. See 'Details'.
#' @return Return the reconciled \code{gts} object or forecasts at the bottom
#' level.
#' @details
#' The \code{control.nn} argument is a list that can supply any of the following components:
#' \describe{
#' \item{\code{ptype}}{Permutation method to be used: \code{"fixed"} or \code{"random"}. Defaults to \code{"fixed"}.}
#' \item{\code{par}}{The number of full exchange rules that may be tried. Defaults to 10.}
#' \item{\code{gtol}}{The tolerance of the convergence criteria. Defaults to \code{sqrt(.Machine$double.eps)}.}
#' }
#' @author Shanika L Wickramasuriya
#' @seealso \code{\link[hts]{hts}}, \code{\link[hts]{gts}},
#' \code{\link[hts]{forecast.gts}}, \code{\link[hts]{combinef}}
#' @references Wickramasuriya, S. L., Athanasopoulos, G., & Hyndman, R. J. (2019).
#' Optimal forecast reconciliation for hierarchical and grouped time series through trace minimization.
#' \emph{Journal of the American Statistical Association}, \bold{114}(526), 804--819. \url{https://robjhyndman.com/working-papers/mint/}
#'
#' Wickramasuriya, S. L., Turlach, B. A., & Hyndman, R. J. (to appear). Optimal non-negative forecast reconciliation.
#' \emph{Statistics and Computing}. \url{https://robjhyndman.com/publications/nnmint/}
#'
#' Hyndman, R. J., Lee, A., & Wang, E. (2016). Fast computation of reconciled
#' forecasts for hierarchical and grouped time series. \emph{Computational
#' Statistics and Data Analysis}, \bold{97}, 16--32.
#' \url{https://robjhyndman.com/publications/hgts/}
#' @keywords ts
#' @examples
#'
#' # hts example
#' \dontrun{
#' h <- 12
#' ally <- aggts(htseg1)
#' n <- nrow(ally)
#' p <- ncol(ally)
#' allf <- matrix(NA, nrow = h, ncol = p)
#' res <- matrix(NA, nrow = n, ncol = p)
#' for(i in 1:p)
#' {
#' fit <- auto.arima(ally[, i])
#' allf[, i] <- forecast(fit, h = h)$mean
#' res[, i] <- na.omit(ally[, i] - fitted(fit))
#' }
#' allf <- ts(allf, start = 51)
#' y.f <- MinT(allf, get_nodes(htseg1), residual = res, covariance = "shr",
#' keep = "gts", algorithms = "lu")
#' plot(y.f)
#' y.f_cg <- MinT(allf, get_nodes(htseg1), residual = res, covariance = "shr",
#' keep = "all", algorithms = "cg")
#' }
#'
#' \dontrun{
#' h <- 12
#' ally <- abs(aggts(htseg2))
#' allf <- matrix(NA, nrow = h, ncol = ncol(ally))
#' res <- matrix(NA, nrow = nrow(ally), ncol = ncol(ally))
#' for(i in 1:ncol(ally)) {
#' fit <- auto.arima(ally[, i], lambda = 0, biasadj = TRUE)
#' allf[,i] <- forecast(fit, h = h)$mean
#' res[,i] <- na.omit(ally[, i] - fitted(fit))
#' }
#' b.f <- MinT(allf, get_nodes(htseg2), residual = res, covariance = "shr",
#' keep = "bottom", algorithms = "lu")
#' b.nnf <- MinT(allf, get_nodes(htseg2), residual = res, covariance = "shr",
#' keep = "bottom", algorithms = "lu", nonnegative = TRUE, parallel = TRUE)
#' }
#'
#' # gts example
#' \dontrun{
#' abc <- ts(5 + matrix(sort(rnorm(200)), ncol = 4, nrow = 50))
#' g <- rbind(c(1,1,2,2), c(1,2,1,2))
#' y <- gts(abc, groups = g)
#' h <- 12
#' ally <- aggts(y)
#' n <- nrow(ally)
#' p <- ncol(ally)
#' allf <- matrix(NA,nrow = h,ncol = ncol(ally))
#' res <- matrix(NA, nrow = n, ncol = p)
#' for(i in 1:p)
#' {
#' fit <- auto.arima(ally[, i])
#' allf[, i] <- forecast(fit, h = h)$mean
#' res[, i] <- na.omit(ally[, i] - fitted(fit))
#' }
#' allf <- ts(allf, start = 51)
#' y.f <- MinT(allf, groups = get_groups(y), residual = res, covariance = "shr",
#' keep = "gts", algorithms = "lu")
#' plot(y.f)
#' }
#' @export MinT
MinT <- function (fcasts, nodes = NULL, groups = NULL, residual, covariance = c("shr", "sam"),
nonnegative = FALSE, algorithms = c("lu", "cg", "chol"),
keep = c("gts", "all", "bottom"), parallel = FALSE, num.cores = 2, control.nn = list())
{
if (is.null(nodes) && is.null(groups)) {
stop("Please specify the hierarchical or the grouping structure.", call. = FALSE)
}
if (!xor(is.null(nodes), is.null(groups))) {
stop("Please specify either nodes or groups argument, not both.", call. = FALSE)
}
alg <- match.arg(algorithms)
keep <- match.arg(keep)
covar <- match.arg(covariance)
res <- residual
fcasts <- stats::as.ts(fcasts)
tspx <- stats::tsp(fcasts)
cnames <- colnames(fcasts)
if (!nonnegative) {
if (missing(residual))
{
stop("MinT needs insample residuals.", call. = FALSE)
}
if (covar=="sam")
{
n <- nrow(res)
w.1 <- crossprod(res) / n
if(is.posdef(w.1)==FALSE)
{
stop("MinT needs covariance matrix to be positive definite.", call. = FALSE)
}
} else {
tar <- lowerD(res)
shrink <- shrink.estim(res, tar)
w.1 <- shrink[[1]]
lambda <- shrink[[2]]
if (is.posdef(w.1)==FALSE)
{
stop("MinT needs covariance matrix to be positive definite.", call. = FALSE)
}
}
if (is.null(groups)) { # hts class
totalts <- sum(Mnodes(nodes))
if (!is.matrix(fcasts)) {
fcasts <- t(fcasts)
}
h <- nrow(fcasts)
if (ncol(fcasts) != totalts) {
stop("Argument fcasts requires all the forecasts.", call. = FALSE)
}
gmat <- GmatrixH(nodes)
fcasts <- t(fcasts)
if (alg == "chol") {
smat <- Smatrix(gmat)
if (!is.null(w.1)) {
w.1 <- as.matrix.csr(w.1)
}
allf <- CHOL(fcasts = fcasts, S = smat, weights = w.1, allow.changes = FALSE)
}
else {
smat <- SmatrixM(gmat)
if (!is.null(w.1)) {
weights <- methods::as(w.1, "sparseMatrix")
}
if (alg == "lu") {
allf <- LU(fcasts = fcasts, S = smat, weights = weights, allow.changes = FALSE)
}
else if (alg == "cg") {
allf <- CG(fcasts = fcasts, S = smat, weights = weights, allow.changes = FALSE)
}
}
if (keep == "all") {
out <- t(allf)
}
else {
bottom <- totalts - (ncol(smat):1L) + 1L
bf <- t(allf[bottom, ])
if (keep == "gts") {
bf <- ts(bf, start = tspx[1L], frequency = tspx[3L])
out <- suppressMessages(hts(bf, nodes = nodes))
}
else {
out <- bf
}
}
}
else if (is.null(nodes)) {
rownames(groups) <- NULL
gmat <- GmatrixG(groups)
totalts <- sum(Mlevel(gmat))
if (ncol(fcasts) != totalts) {
stop("Argument fcasts requires all the forecasts.", call. = FALSE)
}
fcasts <- t(fcasts)
if (alg == "chol") {
smat <- Smatrix(gmat)
if (!is.null(w.1)) {
weights <- as.matrix.csr(w.1)
}
allf <- CHOL(fcasts = fcasts, S = smat, weights = weights, allow.changes = FALSE)
}
else {
smat <- SmatrixM(gmat)
if (!is.null(w.1)) {
weights <- methods::as(w.1, "sparseMatrix")
}
if (alg == "lu") {
allf <- LU(fcasts = fcasts, S = smat, weights = weights, allow.changes = FALSE)
}
else if (alg == "cg") {
allf <- CG(fcasts = fcasts, S = smat, weights = weights, allow.changes = FALSE)
}
}
if (keep == "all") {
out <- t(allf)
}
else {
bottom <- totalts - (ncol(smat):1L) + 1L
bf <- t(allf[bottom, ])
if (keep == "gts") {
colnames(bf) <- cnames[bottom]
bf <- ts(bf, start = tspx[1L], frequency = tspx[3L])
out <- suppressMessages(gts(bf, groups = groups))
}
else {
out <- bf
}
}
}
} else {
if (any(fcasts < 0)) {
fcasts[fcasts < 0] <- 0
warning("Negative base forecasts are truncated to zero.")
}
lst.fc <- split(fcasts, row(fcasts))
if (parallel) {
if (is.null(num.cores)) {
num.cores <- detectCores()
}
cl <- makeCluster(num.cores)
bf <- parSapplyLB(cl = cl, X = lst.fc, MinTbpv, nodes = nodes, groups = groups, res = res, covar = covar, alg = alg, control.nn = control.nn, simplify = TRUE)
stopCluster(cl = cl)
} else {
bf <- sapply(lst.fc, MinTbpv, nodes = nodes, groups = groups, res = res, covar = covar, alg = alg, control.nn = control.nn)
}
bf <- ts(t(bf), start = tspx[1L], frequency = tspx[3L])
if (is.null(groups)) {
if (keep == "bottom") {
out <- bf
} else {
out <- suppressMessages(hts(bf, nodes = nodes))
if (keep == "all") {
out <- aggts(out)
}
}
} else {
if (keep == "bottom") {
out <- bf
} else {
colnames(bf) <- tail(cnames, ncol(bf))
out <- suppressMessages(gts(bf, groups = groups))
if (keep == "all") {
out <- aggts(out)
}
}
}
}
return(out)
}
is.posdef <- function (x, tol = 1e-08) {
n <- NROW(x)
if(n != NCOL(x))
stop("x is not a square matrix")
if(sum(c(abs(x - t(x)))) > 1e-8)
stop("x is not a symmetric matrix")
eigenvalues <- eigen(x, only.values = TRUE)$values
eigenvalues[abs(eigenvalues) < tol] <- 0
all(eigenvalues >= 0)
}