attempt to fix F_Neighbors2
[talweg.git] / pkg / R / F_Neighbors2.R
1 #' @include Forecaster.R
2 #'
3 #' Neighbors2 Forecaster
4 #'
5 #' Predict tomorrow as a weighted combination of "futures of the past" days.
6 #' Inherits \code{\link{Forecaster}}
7 #'
8 Neighbors2Forecaster = R6::R6Class("Neighbors2Forecaster",
9 inherit = Forecaster,
10
11 public = list(
12 predictShape = function(data, today, memory, horizon, ...)
13 {
14 # (re)initialize computed parameters
15 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
16
17 # Do not forecast on days with NAs (TODO: softer condition...)
18 if (any(is.na(data$getCenteredSerie(today))))
19 return (NA)
20
21 # Determine indices of no-NAs days followed by no-NAs tomorrows
22 fdays = getNoNA2(data, max(today-memory,1), today-1)
23
24 # Get optional args
25 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
26 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
27 if (hasArg(h_window))
28 {
29 return ( private$.predictShapeAux(data,
30 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
31 }
32
33 # Indices of similar days for cross-validation; TODO: 20 = magic number
34 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE, days_in=fdays)
35
36 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
37 errorOnLastNdays = function(h, kernel, simtype)
38 {
39 error = 0
40 nb_jours = 0
41 for (i in seq_along(cv_days))
42 {
43 # mix_strategy is never used here (simtype != "mix"), therefore left blank
44 prediction = private$.predictShapeAux(data,
45 fdays, cv_days[i], horizon, h, kernel, simtype, FALSE)
46 if (!is.na(prediction[1]))
47 {
48 nb_jours = nb_jours + 1
49 error = error + mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
50 }
51 }
52 return (error / nb_jours)
53 }
54
55 if (simtype != "endo")
56 {
57 h_best_exo = optimize(
58 errorOnLastNdays, c(0,7), kernel=kernel, simtype="exo")$minimum
59 }
60 if (simtype != "exo")
61 {
62 h_best_endo = optimize(
63 errorOnLastNdays, c(0,7), kernel=kernel, simtype="endo")$minimum
64 }
65
66 if (simtype == "endo")
67 {
68 return (private$.predictShapeAux(data,
69 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
70 }
71 if (simtype == "exo")
72 {
73 return (private$.predictShapeAux(data,
74 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
75 }
76 if (simtype == "mix")
77 {
78 h_best_mix = c(h_best_endo,h_best_exo)
79 return(private$.predictShapeAux(data,
80 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
81 }
82 }
83 ),
84 private = list(
85 # Precondition: "today" is full (no NAs)
86 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
87 {
88 fdays_cut = fdays[ fdays < today ]
89 # TODO: 3 = magic number
90 if (length(fdays_cut) < 3)
91 return (NA)
92
93 # Neighbors: days in "same season"; TODO: 60 == magic number...
94 fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE, 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, 3, 5, 10 magic numbers here...
100 dist_thresh = 2
101 min_neighbs = min(3,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 = 10
112 if (nb_neighbs > max_neighbs)
113 {
114 # Keep only max_neighbs closest neighbors
115 fdays = fdays[ sort(distances[same_pollution],index.return=TRUE)$ix[1:max_neighbs] ]
116 }
117 if (length(fdays) == 1) #the other extreme...
118 {
119 if (final_call)
120 {
121 private$.params$weights <- 1
122 private$.params$indices <- fdays
123 private$.params$window <- 1
124 }
125 return ( data$getSerie(fdays[1])[1:horizon] ) #what else?!
126 }
127
128 if (simtype != "exo")
129 {
130 h_endo = ifelse(simtype=="mix", h[1], h)
131
132 # Distances from last observed day to days in the past
133 serieToday = data$getSerie(today)
134 distances2 = sapply(fdays, function(i) {
135 delta = serieToday - data$getSerie(i)
136 mean(delta^2)
137 })
138
139 sd_dist = sd(distances2)
140 if (sd_dist < .Machine$double.eps)
141 {
142 # warning("All computed distances are very close: stdev too small")
143 sd_dist = 1 #mostly for tests... FIXME:
144 }
145 simils_endo =
146 if (kernel=="Gauss")
147 exp(-distances2/(sd_dist*h_endo^2))
148 else
149 {
150 # Epanechnikov
151 u = 1 - distances2/(sd_dist*h_endo^2)
152 u[abs(u)>1] = 0.
153 u
154 }
155 }
156
157 if (simtype != "endo")
158 {
159 h_exo = ifelse(simtype=="mix", h[2], h)
160
161 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
162 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
163 for (i in seq_along(fdays))
164 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
165
166 sigma = cov(M) #NOTE: robust covariance is way too slow
167 # TODO: 10 == magic number; more robust way == det, or always ginv()
168 sigma_inv =
169 if (length(fdays) > 10)
170 solve(sigma)
171 else
172 MASS::ginv(sigma)
173
174 # Distances from last observed day to days in the past
175 distances2 = sapply(seq_along(fdays), function(i) {
176 delta = M[1,] - M[i+1,]
177 delta %*% sigma_inv %*% delta
178 })
179
180 sd_dist = sd(distances2)
181 if (sd_dist < .25 * sqrt(.Machine$double.eps))
182 {
183 # warning("All computed distances are very close: stdev too small")
184 sd_dist = 1 #mostly for tests... FIXME:
185 }
186 simils_exo =
187 if (kernel=="Gauss")
188 exp(-distances2/(sd_dist*h_exo^2))
189 else
190 {
191 # Epanechnikov
192 u = 1 - distances2/(sd_dist*h_exo^2)
193 u[abs(u)>1] = 0.
194 u
195 }
196 }
197
198 similarities =
199 if (simtype == "exo")
200 simils_exo
201 else if (simtype == "endo")
202 simils_endo
203 else #mix
204 simils_endo * simils_exo
205 similarities = similarities / sum(similarities)
206
207 prediction = rep(0, horizon)
208 for (i in seq_along(fdays))
209 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
210
211 if (final_call)
212 {
213 prediction = prediction - mean(prediction) #predict centered serie (artificial...)
214 private$.params$weights <- similarities
215 private$.params$indices <- fdays
216 private$.params$window <-
217 if (simtype=="endo")
218 h_endo
219 else if (simtype=="exo")
220 h_exo
221 else #mix
222 c(h_endo,h_exo)
223 }
224
225 return (prediction)
226 }
227 )
228 )