| 1 | #' Neighbors Forecaster |
| 2 | #' |
| 3 | #' Predict next serie as a weighted combination of "futures of the past" days, |
| 4 | #' where days in the past are chosen and weighted according to some similarity measures. |
| 5 | #' |
| 6 | #' The main method is \code{predictShape()}, taking arguments data, today, memory, |
| 7 | #' predict_from, horizon respectively for the dataset (object output of |
| 8 | #' \code{getData()}), the current index, the data depth (in days), the first predicted |
| 9 | #' hour and the last predicted hour. |
| 10 | #' In addition, optional arguments can be passed: |
| 11 | #' \itemize{ |
| 12 | #' \item local : TRUE (default) to constrain neighbors to be "same days within same |
| 13 | #' season" |
| 14 | #' \item simtype : 'endo' for a similarity based on the series only,<cr> |
| 15 | #' 'exo' for a similarity based on exogenous variables only,<cr> |
| 16 | #' 'mix' for the product of 'endo' and 'exo',<cr> |
| 17 | #' 'none' (default) to apply a simple average: no computed weights |
| 18 | #' \item window : A window for similarities computations; override cross-validation |
| 19 | #' window estimation. |
| 20 | #' } |
| 21 | #' The method is summarized as follows: |
| 22 | #' \enumerate{ |
| 23 | #' \item Determine N (=20) recent days without missing values, and followed by a |
| 24 | #' tomorrow also without missing values. |
| 25 | #' \item Optimize the window parameters (if relevant) on the N chosen days. |
| 26 | #' \item Considering the optimized window, compute the neighbors (with locality |
| 27 | #' constraint or not), compute their similarities -- using a gaussian kernel if |
| 28 | #' simtype != "none" -- and average accordingly the "tomorrows of neigbors" to |
| 29 | #' obtain the final prediction. |
| 30 | #' } |
| 31 | #' |
| 32 | #' @usage # NeighborsForecaster$new(pjump) |
| 33 | #' |
| 34 | #' @docType class |
| 35 | #' @format R6 class, inherits Forecaster |
| 36 | #' @aliases F_Neighbors |
| 37 | #' |
| 38 | NeighborsForecaster = R6::R6Class("NeighborsForecaster", |
| 39 | inherit = Forecaster, |
| 40 | |
| 41 | public = list( |
| 42 | predictShape = function(data, today, memory, predict_from, horizon, ...) |
| 43 | { |
| 44 | # (re)initialize computed parameters |
| 45 | private$.params <- list("weights"=NA, "indices"=NA, "window"=NA) |
| 46 | |
| 47 | # Do not forecast on days with NAs (TODO: softer condition...) |
| 48 | if (any(is.na(data$getSerie(today-1))) || |
| 49 | (predict_from>=2 && any(is.na(data$getSerie(today)[1:(predict_from-1)])))) |
| 50 | { |
| 51 | return (NA) |
| 52 | } |
| 53 | |
| 54 | # Get optional args |
| 55 | local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season? |
| 56 | simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo" |
| 57 | opera = ifelse(hasArg("opera"), list(...)$opera, FALSE) #operational mode? |
| 58 | |
| 59 | # Determine indices of no-NAs days preceded by no-NAs yerstedays |
| 60 | tdays = .getNoNA2(data, max(today-memory,2), ifelse(opera,today-1,data$getSize())) |
| 61 | if (!opera) |
| 62 | tdays = setdiff(tdays, today) #always exclude current day |
| 63 | |
| 64 | # Shortcut if window is known |
| 65 | if (hasArg("window")) |
| 66 | { |
| 67 | return ( private$.predictShapeAux(data, tdays, today, predict_from, horizon, |
| 68 | local, list(...)$window, simtype, opera, TRUE) ) |
| 69 | } |
| 70 | |
| 71 | # Indices of similar days for cross-validation; TODO: 20 = magic number |
| 72 | cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE, |
| 73 | days_in=tdays, operational=opera) |
| 74 | |
| 75 | # Optimize h : h |--> sum of prediction errors on last N "similar" days |
| 76 | errorOnLastNdays = function(window, simtype) |
| 77 | { |
| 78 | error = 0 |
| 79 | nb_jours = 0 |
| 80 | for (i in seq_along(cv_days)) |
| 81 | { |
| 82 | # mix_strategy is never used here (simtype != "mix"), therefore left blank |
| 83 | prediction = private$.predictShapeAux(data, tdays, cv_days[i], predict_from, |
| 84 | horizon, local, window, simtype, opera, FALSE) |
| 85 | if (!is.na(prediction[1])) |
| 86 | { |
| 87 | nb_jours = nb_jours + 1 |
| 88 | error = error + |
| 89 | mean((data$getSerie(cv_days[i])[predict_from:horizon] - prediction)^2) |
| 90 | } |
| 91 | } |
| 92 | return (error / nb_jours) |
| 93 | } |
| 94 | |
| 95 | # TODO: 7 == magic number |
| 96 | if (simtype=="endo" || simtype=="mix") |
| 97 | { |
| 98 | best_window_endo = optimize( |
| 99 | errorOnLastNdays, c(0,7), simtype="endo")$minimum |
| 100 | } |
| 101 | if (simtype=="exo" || simtype=="mix") |
| 102 | { |
| 103 | best_window_exo = optimize( |
| 104 | errorOnLastNdays, c(0,7), simtype="exo")$minimum |
| 105 | } |
| 106 | |
| 107 | best_window = |
| 108 | if (simtype == "endo") |
| 109 | best_window_endo |
| 110 | else if (simtype == "exo") |
| 111 | best_window_exo |
| 112 | else if (simtype == "mix") |
| 113 | c(best_window_endo,best_window_exo) |
| 114 | else #none: value doesn't matter |
| 115 | 1 |
| 116 | |
| 117 | return( private$.predictShapeAux(data, tdays, today, predict_from, horizon, local, |
| 118 | best_window, simtype, opera, TRUE) ) |
| 119 | } |
| 120 | ), |
| 121 | private = list( |
| 122 | # Precondition: "yersteday until predict_from-1" is full (no NAs) |
| 123 | .predictShapeAux = function(data, tdays, today, predict_from, horizon, local, window, |
| 124 | simtype, opera, final_call) |
| 125 | { |
| 126 | tdays_cut = tdays[ tdays != today ] |
| 127 | if (length(tdays_cut) == 0) |
| 128 | return (NA) |
| 129 | |
| 130 | if (local) |
| 131 | { |
| 132 | # TODO: 60 == magic number |
| 133 | tdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE, |
| 134 | days_in=tdays_cut, operational=opera) |
| 135 | # if (length(tdays) <= 1) |
| 136 | # return (NA) |
| 137 | # TODO: 10 == magic number |
| 138 | tdays = .getConstrainedNeighbs(today, data, tdays, min_neighbs=10) |
| 139 | if (length(tdays) == 1) |
| 140 | { |
| 141 | if (final_call) |
| 142 | { |
| 143 | private$.params$weights <- 1 |
| 144 | private$.params$indices <- tdays |
| 145 | private$.params$window <- 1 |
| 146 | } |
| 147 | return ( data$getSerie(tdays[1])[predict_from:horizon] ) |
| 148 | } |
| 149 | } |
| 150 | else |
| 151 | tdays = tdays_cut #no conditioning |
| 152 | |
| 153 | if (simtype == "endo" || simtype == "mix") |
| 154 | { |
| 155 | # Compute endogen similarities using given window |
| 156 | window_endo = ifelse(simtype=="mix", window[1], window) |
| 157 | |
| 158 | # Distances from last observed day to selected days in the past |
| 159 | distances2 <- .computeDistsEndo(data, today, tdays, predict_from) |
| 160 | |
| 161 | if (local) |
| 162 | { |
| 163 | max_neighbs = 12 #TODO: 12 = arbitrary number |
| 164 | if (length(distances2) > max_neighbs) |
| 165 | { |
| 166 | ordering <- order(distances2) |
| 167 | tdays <- tdays[ ordering[1:max_neighbs] ] |
| 168 | distances2 <- distances2[ ordering[1:max_neighbs] ] |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | simils_endo <- .computeSimils(distances2, window_endo) |
| 173 | } |
| 174 | |
| 175 | if (simtype == "exo" || simtype == "mix") |
| 176 | { |
| 177 | # Compute exogen similarities using given window |
| 178 | window_exo = ifelse(simtype=="mix", window[2], window) |
| 179 | |
| 180 | distances2 <- .computeDistsExo(data, today, tdays) |
| 181 | |
| 182 | simils_exo <- .computeSimils(distances2, window_exo) |
| 183 | } |
| 184 | |
| 185 | similarities = |
| 186 | if (simtype == "exo") |
| 187 | simils_exo |
| 188 | else if (simtype == "endo") |
| 189 | simils_endo |
| 190 | else if (simtype == "mix") |
| 191 | simils_endo * simils_exo |
| 192 | else #none |
| 193 | rep(1, length(tdays)) |
| 194 | similarities = similarities / sum(similarities) |
| 195 | |
| 196 | prediction = rep(0, horizon-predict_from+1) |
| 197 | for (i in seq_along(tdays)) |
| 198 | { |
| 199 | prediction = prediction + |
| 200 | similarities[i] * data$getSerie(tdays[i])[predict_from:horizon] |
| 201 | } |
| 202 | |
| 203 | if (final_call) |
| 204 | { |
| 205 | private$.params$weights <- similarities |
| 206 | private$.params$indices <- tdays |
| 207 | private$.params$window <- |
| 208 | if (simtype=="endo") |
| 209 | window_endo |
| 210 | else if (simtype=="exo") |
| 211 | window_exo |
| 212 | else if (simtype=="mix") |
| 213 | c(window_endo,window_exo) |
| 214 | else #none |
| 215 | 1 |
| 216 | } |
| 217 | |
| 218 | return (prediction) |
| 219 | } |
| 220 | ) |
| 221 | ) |
| 222 | |
| 223 | # getConstrainedNeighbs |
| 224 | # |
| 225 | # Get indices of neighbors of similar pollution level (among same season + day type). |
| 226 | # |
| 227 | # @param today Index of current day |
| 228 | # @param data Object of class Data |
| 229 | # @param tdays Current set of "second days" (no-NA pairs) |
| 230 | # @param min_neighbs Minimum number of points in a neighborhood |
| 231 | # @param max_neighbs Maximum number of points in a neighborhood |
| 232 | # |
| 233 | .getConstrainedNeighbs = function(today, data, tdays, min_neighbs=10) |
| 234 | { |
| 235 | levelToday = data$getLevelHat(today) |
| 236 | # levelYersteday = data$getLevel(today-1) |
| 237 | distances = sapply(tdays, function(i) { |
| 238 | # sqrt((data$getLevel(i-1)-levelYersteday)^2 + (data$getLevel(i)-levelToday)^2) |
| 239 | abs(data$getLevel(i)-levelToday) |
| 240 | }) |
| 241 | #TODO: 1, +1, +3 : magic numbers |
| 242 | dist_thresh = 1 |
| 243 | min_neighbs = min(min_neighbs,length(tdays)) |
| 244 | repeat |
| 245 | { |
| 246 | same_pollution = (distances <= dist_thresh) |
| 247 | nb_neighbs = sum(same_pollution) |
| 248 | if (nb_neighbs >= min_neighbs) #will eventually happen |
| 249 | break |
| 250 | dist_thresh = dist_thresh + ifelse(dist_thresh>1,3,1) |
| 251 | } |
| 252 | tdays = tdays[same_pollution] |
| 253 | # max_neighbs = 12 |
| 254 | # if (nb_neighbs > max_neighbs) |
| 255 | # { |
| 256 | # # Keep only max_neighbs closest neighbors |
| 257 | # tdays = tdays[ order(distances[same_pollution])[1:max_neighbs] ] |
| 258 | # } |
| 259 | tdays |
| 260 | } |
| 261 | |
| 262 | # compute similarities |
| 263 | # |
| 264 | # Apply the gaussian kernel on computed squared distances. |
| 265 | # |
| 266 | # @param distances2 Squared distances |
| 267 | # @param window Window parameter for the kernel |
| 268 | # |
| 269 | .computeSimils <- function(distances2, window) |
| 270 | { |
| 271 | sd_dist = sd(distances2) |
| 272 | if (sd_dist < .25 * sqrt(.Machine$double.eps)) |
| 273 | { |
| 274 | # warning("All computed distances are very close: stdev too small") |
| 275 | sd_dist = 1 #mostly for tests... FIXME: |
| 276 | } |
| 277 | exp(-distances2/(sd_dist*window^2)) |
| 278 | } |
| 279 | |
| 280 | .computeDistsEndo <- function(data, today, tdays, predict_from) |
| 281 | { |
| 282 | lastSerie = c( data$getSerie(today-1), |
| 283 | data$getSerie(today)[if (predict_from>=2) 1:(predict_from-1) else c()] ) |
| 284 | sapply(tdays, function(i) { |
| 285 | delta = lastSerie - c(data$getSerie(i-1), |
| 286 | data$getSerie(i)[if (predict_from>=2) 1:(predict_from-1) else c()]) |
| 287 | sqrt(mean(delta^2)) |
| 288 | }) |
| 289 | } |
| 290 | |
| 291 | .computeDistsExo <- function(data, today, tdays) |
| 292 | { |
| 293 | M = matrix( ncol=1+length(tdays), nrow=1+length(data$getExo(1)) ) |
| 294 | M[,1] = c( data$getLevelHat(today), as.double(data$getExoHat(today)) ) |
| 295 | for (i in seq_along(tdays)) |
| 296 | M[,i+1] = c( data$getLevel(tdays[i]), as.double(data$getExo(tdays[i])) ) |
| 297 | |
| 298 | sigma = cov(t(M)) #NOTE: robust covariance is way too slow |
| 299 | # TODO: 10 == magic number; more robust way == det, or always ginv() |
| 300 | sigma_inv = |
| 301 | if (length(tdays) > 10) |
| 302 | solve(sigma) |
| 303 | else |
| 304 | MASS::ginv(sigma) |
| 305 | |
| 306 | # Distances from last observed day to days in the past |
| 307 | sapply(seq_along(tdays), function(i) { |
| 308 | delta = M[,1] - M[,i+1] |
| 309 | delta %*% sigma_inv %*% delta |
| 310 | }) |
| 311 | } |