52c2b35bfb31e168fbe3b4750761c6bd04d4edfa
[talweg.git] / pkg / R / F_Neighbors.R
1 #' Neighbors Forecaster
2 #'
3 #' Predict tomorrow as a weighted combination of "futures of the past" days.
4 #' Inherits \code{\link{Forecaster}}
5 #'
6 NeighborsForecaster = R6::R6Class("NeighborsForecaster",
7 inherit = Forecaster,
8
9 public = list(
10 predictShape = function(data, today, memory, horizon, ...)
11 {
12 # (re)initialize computed parameters
13 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
14
15 # Do not forecast on days with NAs (TODO: softer condition...)
16 if (any(is.na(data$getCenteredSerie(today))))
17 return (NA)
18
19 # Determine indices of no-NAs days followed by no-NAs tomorrows
20 fdays = getNoNA2(data, max(today-memory,1), today-1)
21
22 # Get optional args
23 local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
24 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
25 if (hasArg("window"))
26 {
27 return ( private$.predictShapeAux(data,
28 fdays, today, horizon, local, list(...)$window, simtype, TRUE) )
29 }
30
31 # Indices of similar days for cross-validation; TODO: 20 = magic number
32 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE,
33 days_in=fdays)
34
35 # Optimize h : h |--> sum of prediction errors on last N "similar" days
36 errorOnLastNdays = function(window, simtype)
37 {
38 error = 0
39 nb_jours = 0
40 for (i in seq_along(cv_days))
41 {
42 # mix_strategy is never used here (simtype != "mix"), therefore left blank
43 prediction = private$.predictShapeAux(data, fdays, cv_days[i], horizon, local,
44 window, simtype, FALSE)
45 if (!is.na(prediction[1]))
46 {
47 nb_jours = nb_jours + 1
48 error = error +
49 mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
50 }
51 }
52 return (error / nb_jours)
53 }
54
55 # TODO: 7 == magic number
56 if (simtype=="endo" || simtype=="mix")
57 {
58 best_window_endo = optimize(
59 errorOnLastNdays, c(0,7), simtype="endo")$minimum
60 }
61 if (simtype=="exo" || simtype=="mix")
62 {
63 best_window_exo = optimize(
64 errorOnLastNdays, c(0,7), simtype="exo")$minimum
65 }
66
67 best_window =
68 if (simtype == "endo")
69 best_window_endo
70 else if (simtype == "exo")
71 best_window_exo
72 else if (simtype == "mix")
73 c(best_window_endo,best_window_exo)
74 else #none: value doesn't matter
75 1
76
77 return(private$.predictShapeAux(data, fdays, today, horizon, local,
78 best_window, simtype, TRUE))
79 }
80 ),
81 private = list(
82 # Precondition: "today" is full (no NAs)
83 .predictShapeAux = function(data, fdays, today, horizon, local, window, simtype,
84 final_call)
85 {
86 fdays_cut = fdays[ fdays < today ]
87 if (length(fdays_cut) <= 1)
88 return (NA)
89
90 if (local)
91 {
92 # Neighbors: days in "same season"; TODO: 60 == magic number...
93 fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE,
94 days_in=fdays_cut)
95 if (length(fdays) <= 1)
96 return (NA)
97 levelToday = data$getLevel(today)
98 distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
99 #TODO: 2, 10, 3, 12 magic numbers here...
100 dist_thresh = 2
101 min_neighbs = min(10,length(fdays))
102 repeat
103 {
104 same_pollution = (distances <= dist_thresh)
105 nb_neighbs = sum(same_pollution)
106 if (nb_neighbs >= min_neighbs) #will eventually happen
107 break
108 dist_thresh = dist_thresh + 3
109 }
110 fdays = fdays[same_pollution]
111 max_neighbs = 12
112 if (nb_neighbs > max_neighbs)
113 {
114 # Keep only max_neighbs closest neighbors
115 fdays = fdays[
116 sort(distances[same_pollution],index.return=TRUE)$ix[1:max_neighbs] ]
117 }
118 if (length(fdays) == 1) #the other extreme...
119 {
120 if (final_call)
121 {
122 private$.params$weights <- 1
123 private$.params$indices <- fdays
124 private$.params$window <- 1
125 }
126 return ( data$getSerie(fdays[1])[1:horizon] )
127 }
128 }
129 else
130 fdays = fdays_cut #no conditioning
131
132 if (simtype == "endo" || simtype == "mix")
133 {
134 # Compute endogen similarities using given window
135 window_endo = ifelse(simtype=="mix", window[1], window)
136
137 # Distances from last observed day to days in the past
138 serieToday = data$getSerie(today)
139 distances2 = sapply(fdays, function(i) {
140 delta = serieToday - data$getSerie(i)
141 mean(delta^2)
142 })
143
144 sd_dist = sd(distances2)
145 if (sd_dist < .25 * sqrt(.Machine$double.eps))
146 {
147 # warning("All computed distances are very close: stdev too small")
148 sd_dist = 1 #mostly for tests... FIXME:
149 }
150 simils_endo = exp(-distances2/(sd_dist*window_endo^2))
151 }
152
153 if (simtype == "exo" || simtype == "mix")
154 {
155 # Compute exogen similarities using given window
156 window_exo = ifelse(simtype=="mix", window[2], window)
157
158 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
159 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
160 for (i in seq_along(fdays))
161 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
162
163 sigma = cov(M) #NOTE: robust covariance is way too slow
164 # TODO: 10 == magic number; more robust way == det, or always ginv()
165 sigma_inv =
166 if (length(fdays) > 10)
167 solve(sigma)
168 else
169 MASS::ginv(sigma)
170
171 # Distances from last observed day to days in the past
172 distances2 = sapply(seq_along(fdays), function(i) {
173 delta = M[1,] - M[i+1,]
174 delta %*% sigma_inv %*% delta
175 })
176
177 sd_dist = sd(distances2)
178 if (sd_dist < .25 * sqrt(.Machine$double.eps))
179 {
180 # warning("All computed distances are very close: stdev too small")
181 sd_dist = 1 #mostly for tests... FIXME:
182 }
183 simils_exo = exp(-distances2/(sd_dist*window_exo^2))
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 )