fix mistake in yersteday/today computations
[talweg.git] / pkg / R / F_Neighbors.R
CommitLineData
25b75559 1#' Neighbors Forecaster
3d69ff21 2#'
c4c329f6
BA
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.
c4c329f6 5#'
102bcfda 6#' The main method is \code{predictShape()}, taking arguments data, today, memory,
d2ab47a7
BA
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.
102bcfda
BA
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>
d2ab47a7 15#' 'exo' for a similarity based on exogenous variables only,<cr>
102bcfda
BA
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#' }
c4c329f6 31#'
4e821712 32#' @usage # NeighborsForecaster$new(pjump)
689aa1d3 33#'
102bcfda 34#' @docType class
c4c329f6 35#' @format R6 class, inherits Forecaster
3ddf1c12 36#' @aliases F_Neighbors
546b0cb6 37#'
25b75559 38NeighborsForecaster = R6::R6Class("NeighborsForecaster",
a66a84b5 39 inherit = Forecaster,
25b75559
BA
40
41 public = list(
d2ab47a7 42 predictShape = function(data, today, memory, predict_from, horizon, ...)
3d69ff21
BA
43 {
44 # (re)initialize computed parameters
a66a84b5 45 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
3d69ff21 46
a5a3a294 47 # Do not forecast on days with NAs (TODO: softer condition...)
cf3bb001
BA
48 if (any(is.na(data$getSerie(today-1))) ||
49 (predict_from>=2 && any(is.na(data$getSerie(today)[1:(predict_from-1)]))))
d2ab47a7 50 {
a5a3a294 51 return (NA)
d2ab47a7 52 }
a5a3a294 53
cf3bb001
BA
54 # Determine indices of no-NAs days preceded by no-NAs yerstedays
55 tdays = .getNoNA2(data, max(today-memory,2), today-1)
af3b84f4 56
f17665c7 57 # Get optional args
445e7bbc
BA
58 local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
59 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
aa059de7 60 if (hasArg("window"))
a66a84b5 61 {
98e958ca 62 return ( private$.predictShapeAux(data,
cf3bb001 63 tdays, today, predict_from, horizon, local, list(...)$window, simtype, TRUE) )
a66a84b5 64 }
3d69ff21 65
6774e53d 66 # Indices of similar days for cross-validation; TODO: 20 = magic number
aa059de7 67 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE,
cf3bb001 68 days_in=tdays)
5e838b3e 69
445e7bbc 70 # Optimize h : h |--> sum of prediction errors on last N "similar" days
aa059de7 71 errorOnLastNdays = function(window, simtype)
3d69ff21
BA
72 {
73 error = 0
74 nb_jours = 0
5e838b3e 75 for (i in seq_along(cv_days))
3d69ff21 76 {
f17665c7 77 # mix_strategy is never used here (simtype != "mix"), therefore left blank
cf3bb001 78 prediction = private$.predictShapeAux(data, tdays, cv_days[i], predict_from,
d2ab47a7 79 horizon, local, window, simtype, FALSE)
f17665c7 80 if (!is.na(prediction[1]))
3d69ff21
BA
81 {
82 nb_jours = nb_jours + 1
af3b84f4 83 error = error +
cf3bb001 84 mean((data$getSerie(cv_days[i])[predict_from:horizon] - prediction)^2)
3d69ff21
BA
85 }
86 }
87 return (error / nb_jours)
88 }
89
445e7bbc 90 # TODO: 7 == magic number
eef54517 91 if (simtype=="endo" || simtype=="mix")
af3b84f4 92 {
aa059de7
BA
93 best_window_endo = optimize(
94 errorOnLastNdays, c(0,7), simtype="endo")$minimum
af3b84f4 95 }
eef54517 96 if (simtype=="exo" || simtype=="mix")
af3b84f4 97 {
eef54517
BA
98 best_window_exo = optimize(
99 errorOnLastNdays, c(0,7), simtype="exo")$minimum
3d69ff21 100 }
eef54517
BA
101
102 best_window =
103 if (simtype == "endo")
104 best_window_endo
105 else if (simtype == "exo")
106 best_window_exo
107 else if (simtype == "mix")
108 c(best_window_endo,best_window_exo)
109 else #none: value doesn't matter
110 1
111
cf3bb001 112 return( private$.predictShapeAux(data, tdays, today, predict_from, horizon, local,
d2ab47a7 113 best_window, simtype, TRUE) )
25b75559
BA
114 }
115 ),
116 private = list(
3d69ff21 117 # Precondition: "today" is full (no NAs)
cf3bb001 118 .predictShapeAux = function(data, tdays, today, predict_from, horizon, local, window,
d2ab47a7 119 simtype, final_call)
3d69ff21 120 {
cf3bb001
BA
121 tdays_cut = tdays[ tdays <= today-1 ]
122 if (length(tdays_cut) <= 1)
3d69ff21
BA
123 return (NA)
124
aa059de7
BA
125 if (local)
126 {
3ddf1c12 127 # TODO: 60 == magic number
cf3bb001
BA
128 tdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE,
129 days_in=tdays_cut)
130 if (length(tdays) <= 1)
aa059de7 131 return (NA)
3ddf1c12 132 # TODO: 10, 12 == magic numbers
cf3bb001
BA
133 tdays = .getConstrainedNeighbs(today,data,tdays,min_neighbs=10,max_neighbs=12)
134 if (length(tdays) == 1)
aa059de7
BA
135 {
136 if (final_call)
137 {
138 private$.params$weights <- 1
cf3bb001 139 private$.params$indices <- tdays
aa059de7
BA
140 private$.params$window <- 1
141 }
cf3bb001 142 return ( data$getSerie(tdays[1])[predict_from:horizon] )
aa059de7
BA
143 }
144 }
145 else
cf3bb001 146 tdays = tdays_cut #no conditioning
aa059de7 147
445e7bbc 148 if (simtype == "endo" || simtype == "mix")
3d69ff21 149 {
aa059de7
BA
150 # Compute endogen similarities using given window
151 window_endo = ifelse(simtype=="mix", window[1], window)
3d69ff21
BA
152
153 # Distances from last observed day to days in the past
cf3bb001
BA
154 lastSerie = c( data$getSerie(today-1),
155 data$getSerie(today)[if (predict_from>=2) 1:(predict_from-1) else c()] )
156 distances2 = sapply(tdays, function(i) {
157 delta = lastSerie - c(data$getSerie(i-1),
158 data$getSerie(i)[if (predict_from>=2) 1:(predict_from-1) else c()])
d2ab47a7 159 sqrt(mean(delta^2))
5e838b3e 160 })
3d69ff21 161
3ddf1c12 162 simils_endo <- .computeSimils(distances2, window_endo)
3d69ff21
BA
163 }
164
445e7bbc 165 if (simtype == "exo" || simtype == "mix")
3d69ff21 166 {
aa059de7 167 # Compute exogen similarities using given window
445e7bbc 168 window_exo = ifelse(simtype=="mix", window[2], window)
3d69ff21 169
cf3bb001 170 M = matrix( ncol=1+length(tdays), nrow=1+length(data$getExo(1)) )
d2ab47a7 171 M[,1] = c( data$getLevelHat(today), as.double(data$getExoHat(today)) )
cf3bb001
BA
172 for (i in seq_along(tdays))
173 M[,i+1] = c( data$getLevel(tdays[i]), as.double(data$getExo(tdays[i])) )
3d69ff21 174
d2ab47a7 175 sigma = cov(t(M)) #NOTE: robust covariance is way too slow
ee8b1b4e
BA
176 # TODO: 10 == magic number; more robust way == det, or always ginv()
177 sigma_inv =
cf3bb001 178 if (length(tdays) > 10)
ee8b1b4e
BA
179 solve(sigma)
180 else
181 MASS::ginv(sigma)
3d69ff21
BA
182
183 # Distances from last observed day to days in the past
cf3bb001 184 distances2 = sapply(seq_along(tdays), function(i) {
d2ab47a7 185 delta = M[,1] - M[,i+1]
5e838b3e
BA
186 delta %*% sigma_inv %*% delta
187 })
3d69ff21 188
3ddf1c12 189 simils_exo <- .computeSimils(distances2, window_exo)
3d69ff21
BA
190 }
191
3d69ff21 192 similarities =
f17665c7 193 if (simtype == "exo")
3d69ff21 194 simils_exo
f17665c7
BA
195 else if (simtype == "endo")
196 simils_endo
445e7bbc 197 else if (simtype == "mix")
f17665c7 198 simils_endo * simils_exo
445e7bbc 199 else #none
cf3bb001 200 rep(1, length(tdays))
ea5c7e56 201 similarities = similarities / sum(similarities)
3d69ff21 202
d2ab47a7 203 prediction = rep(0, horizon-predict_from+1)
cf3bb001 204 for (i in seq_along(tdays))
d2ab47a7
BA
205 {
206 prediction = prediction +
cf3bb001 207 similarities[i] * data$getSerie(tdays[i])[predict_from:horizon]
d2ab47a7 208 }
99f83c9a 209
3d69ff21
BA
210 if (final_call)
211 {
a66a84b5 212 private$.params$weights <- similarities
cf3bb001 213 private$.params$indices <- tdays
a66a84b5 214 private$.params$window <-
546b0cb6 215 if (simtype=="endo")
aa059de7 216 window_endo
546b0cb6 217 else if (simtype=="exo")
aa059de7 218 window_exo
eef54517 219 else if (simtype=="mix")
aa059de7 220 c(window_endo,window_exo)
eef54517
BA
221 else #none
222 1
3d69ff21 223 }
99f83c9a 224
3d69ff21
BA
225 return (prediction)
226 }
227 )
228)
3ddf1c12 229
689aa1d3
BA
230# getConstrainedNeighbs
231#
232# Get indices of neighbors of similar pollution level (among same season + day type).
233#
234# @param today Index of current day
235# @param data Object of class Data
cf3bb001 236# @param tdays Current set of "second days" (no-NA pairs)
689aa1d3
BA
237# @param min_neighbs Minimum number of points in a neighborhood
238# @param max_neighbs Maximum number of points in a neighborhood
239#
cf3bb001 240.getConstrainedNeighbs = function(today, data, tdays, min_neighbs=10, max_neighbs=12)
3ddf1c12 241{
d2ab47a7
BA
242 levelToday = data$getLevelHat(today)
243 levelYersteday = data$getLevel(today-1)
cf3bb001
BA
244 distances = sapply(tdays, function(i) {
245 sqrt((data$getLevel(i-1)-levelYersteday)^2 + (data$getLevel(i)-levelToday)^2)
d2ab47a7
BA
246 })
247 #TODO: 1, +1, +3 : magic numbers
248 dist_thresh = 1
cf3bb001 249 min_neighbs = min(min_neighbs,length(tdays))
3ddf1c12
BA
250 repeat
251 {
252 same_pollution = (distances <= dist_thresh)
253 nb_neighbs = sum(same_pollution)
254 if (nb_neighbs >= min_neighbs) #will eventually happen
255 break
d2ab47a7 256 dist_thresh = dist_thresh + ifelse(dist_thresh>1,3,1)
3ddf1c12 257 }
cf3bb001 258 tdays = tdays[same_pollution]
3ddf1c12
BA
259 max_neighbs = 12
260 if (nb_neighbs > max_neighbs)
261 {
262 # Keep only max_neighbs closest neighbors
cf3bb001 263 tdays = tdays[ order(distances[same_pollution])[1:max_neighbs] ]
3ddf1c12 264 }
cf3bb001 265 tdays
3ddf1c12
BA
266}
267
689aa1d3
BA
268# compute similarities
269#
270# Apply the gaussian kernel on computed squared distances.
271#
272# @param distances2 Squared distances
273# @param window Window parameter for the kernel
274#
3ddf1c12
BA
275.computeSimils <- function(distances2, window)
276{
277 sd_dist = sd(distances2)
278 if (sd_dist < .25 * sqrt(.Machine$double.eps))
279 {
280# warning("All computed distances are very close: stdev too small")
281 sd_dist = 1 #mostly for tests... FIXME:
282 }
283 exp(-distances2/(sd_dist*window^2))
284}