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