1 #' Neighbors Forecaster
3 #' Predict next serie as a weighted combination of curves observed on "similar" days in
4 #' the past (and future if 'opera'=FALSE); the nature of the similarity is controlled by
5 #' the options 'simtype' and 'local' (see below).
9 #' \item local: TRUE (default) to constrain neighbors to be "same days in same season"
10 #' \item simtype: 'endo' for a similarity based on the series only,<cr>
11 #' 'exo' for a similarity based on exogenous variables only,<cr>
12 #' 'mix' for the product of 'endo' and 'exo',<cr>
13 #' 'none' (default) to apply a simple average: no computed weights
14 #' \item window: A window for similarities computations; override cross-validation
17 #' The method is summarized as follows:
19 #' \item Determine N (=20) recent days without missing values, and preceded by a
20 #' curve also without missing values.
21 #' \item Optimize the window parameters (if relevant) on the N chosen days.
22 #' \item Considering the optimized window, compute the neighbors (with locality
23 #' constraint or not), compute their similarities -- using a gaussian kernel if
24 #' simtype != "none" -- and average accordingly the "tomorrows of neigbors" to
25 #' obtain the final prediction.
28 #' @usage # NeighborsForecaster$new(pjump)
31 #' @format R6 class, inherits Forecaster
32 #' @aliases F_Neighbors
34 NeighborsForecaster = R6::R6Class("NeighborsForecaster",
38 predictShape = function(data, today, memory, predict_from, horizon, ...)
40 # (re)initialize computed parameters
41 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
43 # Do not forecast on days with NAs (TODO: softer condition...)
44 if (any(is.na(data$getSerie(today-1))) ||
45 (predict_from>=2 && any(is.na(data$getSerie(today)[1:(predict_from-1)]))))
51 local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
52 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
53 opera = ifelse(hasArg("opera"), list(...)$opera, FALSE) #operational mode?
55 # Determine indices of no-NAs days preceded by no-NAs yerstedays
56 tdays = .getNoNA2(data, max(today-memory,2), ifelse(opera,today-1,data$getSize()))
58 tdays = setdiff(tdays, today) #always exclude current day
60 # Shortcut if window is known or local==TRUE && simtype==none
61 if (hasArg("window") || (local && simtype=="none"))
63 return ( private$.predictShapeAux(data, tdays, today, predict_from, horizon,
64 local, list(...)$window, simtype, opera, TRUE) )
67 # Indices of similar days for cross-validation; TODO: 20 = magic number
68 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE,
69 days_in=tdays, operational=opera)
71 # Optimize h : h |--> sum of prediction errors on last N "similar" days
72 errorOnLastNdays = function(window, simtype)
76 for (i in seq_along(cv_days))
78 # mix_strategy is never used here (simtype != "mix"), therefore left blank
79 prediction = private$.predictShapeAux(data, tdays, cv_days[i], predict_from,
80 horizon, local, window, simtype, opera, FALSE)
81 if (!is.na(prediction[1]))
83 nb_jours = nb_jours + 1
85 mean((data$getSerie(cv_days[i])[predict_from:horizon] - prediction)^2)
88 return (error / nb_jours)
91 # TODO: 7 == magic number
92 if (simtype=="endo" || simtype=="mix")
94 best_window_endo = optimize(
95 errorOnLastNdays, c(0,7), simtype="endo")$minimum
97 if (simtype=="exo" || simtype=="mix")
99 best_window_exo = optimize(
100 errorOnLastNdays, c(0,7), simtype="exo")$minimum
104 if (simtype == "endo")
106 else if (simtype == "exo")
108 else if (simtype == "mix")
109 c(best_window_endo,best_window_exo)
110 else #none: value doesn't matter
113 return( private$.predictShapeAux(data, tdays, today, predict_from, horizon, local,
114 best_window, simtype, opera, TRUE) )
118 # Precondition: "yersteday until predict_from-1" is full (no NAs)
119 .predictShapeAux = function(data, tdays, today, predict_from, horizon, local, window,
120 simtype, opera, final_call)
122 tdays_cut = tdays[ tdays != today ]
123 if (length(tdays_cut) == 0)
128 # limit=Inf to not censor any day (TODO: finite limit? 60?)
129 tdays = getSimilarDaysIndices(today, data, limit=Inf, same_season=TRUE,
130 days_in=tdays_cut, operational=opera)
131 # TODO: 10 == magic number
132 tdays = .getConstrainedNeighbs(today, data, tdays, min_neighbs=10)
133 if (length(tdays) == 1)
137 private$.params$weights <- 1
138 private$.params$indices <- tdays
139 private$.params$window <- 1
141 return ( data$getSerie(tdays[1])[predict_from:horizon] )
143 max_neighbs = 10 #TODO: 10 or 12 or... ?
144 if (length(tdays) > max_neighbs)
146 distances2 <- .computeDistsEndo(data, today, tdays, predict_from)
147 ordering <- order(distances2)
148 tdays <- tdays[ ordering[1:max_neighbs] ]
152 tdays = tdays_cut #no conditioning
154 if (simtype == "endo" || simtype == "mix")
156 # Compute endogen similarities using given window
157 window_endo = ifelse(simtype=="mix", window[1], window)
159 # Distances from last observed day to selected days in the past
160 # TODO: redundant computation if local==TRUE
161 distances2 <- .computeDistsEndo(data, today, tdays, predict_from)
163 simils_endo <- .computeSimils(distances2, window_endo)
166 if (simtype == "exo" || simtype == "mix")
168 # Compute exogen similarities using given window
169 window_exo = ifelse(simtype=="mix", window[2], window)
171 distances2 <- .computeDistsExo(data, today, tdays)
173 simils_exo <- .computeSimils(distances2, window_exo)
177 if (simtype == "exo")
179 else if (simtype == "endo")
181 else if (simtype == "mix")
182 simils_endo * simils_exo
184 rep(1, length(tdays))
185 similarities = similarities / sum(similarities)
187 prediction = rep(0, horizon-predict_from+1)
188 for (i in seq_along(tdays))
190 prediction = prediction +
191 similarities[i] * data$getSerie(tdays[i])[predict_from:horizon]
196 private$.params$weights <- similarities
197 private$.params$indices <- tdays
198 private$.params$window <-
201 else if (simtype=="exo")
203 else if (simtype=="mix")
204 c(window_endo,window_exo)
214 # getConstrainedNeighbs
216 # Get indices of neighbors of similar pollution level (among same season + day type).
218 # @param today Index of current day
219 # @param data Object of class Data
220 # @param tdays Current set of "second days" (no-NA pairs)
221 # @param min_neighbs Minimum number of points in a neighborhood
222 # @param max_neighbs Maximum number of points in a neighborhood
224 .getConstrainedNeighbs = function(today, data, tdays, min_neighbs=10)
226 levelToday = data$getLevelHat(today)
227 distances = sapply( tdays, function(i) abs(data$getLevel(i) - levelToday) )
228 #TODO: 1, +1, +3 : magic numbers
230 min_neighbs = min(min_neighbs,length(tdays))
233 same_pollution = (distances <= dist_thresh)
234 nb_neighbs = sum(same_pollution)
235 if (nb_neighbs >= min_neighbs) #will eventually happen
237 dist_thresh = dist_thresh + ifelse(dist_thresh>1,3,1)
239 tdays[same_pollution]
242 # compute similarities
244 # Apply the gaussian kernel on computed squared distances.
246 # @param distances2 Squared distances
247 # @param window Window parameter for the kernel
249 .computeSimils <- function(distances2, window)
251 sd_dist = sd(distances2)
252 if (sd_dist < .25 * sqrt(.Machine$double.eps))
254 # warning("All computed distances are very close: stdev too small")
255 sd_dist = 1 #mostly for tests... FIXME:
257 exp(-distances2/(sd_dist*window^2))
260 .computeDistsEndo <- function(data, today, tdays, predict_from)
262 lastSerie = c( data$getSerie(today-1),
263 data$getSerie(today)[if (predict_from>=2) 1:(predict_from-1) else c()] )
264 sapply(tdays, function(i) {
265 delta = lastSerie - c(data$getSerie(i-1),
266 data$getSerie(i)[if (predict_from>=2) 1:(predict_from-1) else c()])
271 .computeDistsExo <- function(data, today, tdays)
273 M = matrix( ncol=1+length(tdays), nrow=1+length(data$getExo(1)) )
274 M[,1] = c( data$getLevelHat(today), as.double(data$getExoHat(today)) )
275 for (i in seq_along(tdays))
276 M[,i+1] = c( data$getLevel(tdays[i]), as.double(data$getExo(tdays[i])) )
278 sigma = cov(t(M)) #NOTE: robust covariance is way too slow
279 # TODO: 10 == magic number; more robust way == det, or always ginv()
281 if (length(tdays) > 10)
286 # Distances from last observed day to days in the past
287 sapply(seq_along(tdays), function(i) {
288 delta = M[,1] - M[,i+1]
289 delta %*% sigma_inv %*% delta