attempt to fix F_Neighbors2
[talweg.git] / pkg / R / F_Neighbors2.R
CommitLineData
5c49f6ce
BA
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#'
8Neighbors2Forecaster = 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
9db234c5 22 fdays = getNoNA2(data, max(today-memory,1), today-1)
5c49f6ce
BA
23
24 # Get optional args
5e838b3e 25 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
5c49f6ce
BA
26 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
27 if (hasArg(h_window))
28 {
29 return ( private$.predictShapeAux(data,
5e838b3e 30 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
5c49f6ce
BA
31 }
32
6774e53d
BA
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)
5e838b3e 35
5c49f6ce 36 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
5e838b3e 37 errorOnLastNdays = function(h, kernel, simtype)
5c49f6ce
BA
38 {
39 error = 0
40 nb_jours = 0
5e838b3e 41 for (i in seq_along(cv_days))
5c49f6ce
BA
42 {
43 # mix_strategy is never used here (simtype != "mix"), therefore left blank
5e838b3e
BA
44 prediction = private$.predictShapeAux(data,
45 fdays, cv_days[i], horizon, h, kernel, simtype, FALSE)
5c49f6ce
BA
46 if (!is.na(prediction[1]))
47 {
48 nb_jours = nb_jours + 1
9003747b 49 error = error + mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
5c49f6ce
BA
50 }
51 }
52 return (error / nb_jours)
53 }
54
5e838b3e
BA
55 if (simtype != "endo")
56 {
57 h_best_exo = optimize(
ea5c7e56 58 errorOnLastNdays, c(0,7), kernel=kernel, simtype="exo")$minimum
5e838b3e
BA
59 }
60 if (simtype != "exo")
61 {
62 h_best_endo = optimize(
ea5c7e56 63 errorOnLastNdays, c(0,7), kernel=kernel, simtype="endo")$minimum
5e838b3e
BA
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 }
5c49f6ce
BA
82 }
83 ),
84 private = list(
85 # Precondition: "today" is full (no NAs)
5e838b3e 86 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
5c49f6ce 87 {
6774e53d 88 fdays_cut = fdays[ fdays < today ]
5c49f6ce 89 # TODO: 3 = magic number
6774e53d 90 if (length(fdays_cut) < 3)
5c49f6ce
BA
91 return (NA)
92
6774e53d
BA
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)
ee8b1b4e 96 return (NA)
9db234c5 97 levelToday = data$getLevel(today)
6774e53d 98 distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
ea5c7e56
BA
99 #TODO: 2, 3, 5, 10 magic numbers here...
100 dist_thresh = 2
101 min_neighbs = min(3,length(fdays))
6774e53d 102 repeat
5c49f6ce 103 {
6774e53d 104 same_pollution = (distances <= dist_thresh)
ea5c7e56
BA
105 nb_neighbs = sum(same_pollution)
106 if (nb_neighbs >= min_neighbs) #will eventually happen
6774e53d 107 break
ea5c7e56 108 dist_thresh = dist_thresh + 3
5c49f6ce 109 }
6774e53d 110 fdays = fdays[same_pollution]
ea5c7e56
BA
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...
a866acb3
BA
118 {
119 if (final_call)
120 {
121 private$.params$weights <- 1
6774e53d 122 private$.params$indices <- fdays
a866acb3
BA
123 private$.params$window <- 1
124 }
6774e53d 125 return ( data$getSerie(fdays[1])[1:horizon] ) #what else?!
a866acb3
BA
126 }
127
5e838b3e
BA
128 if (simtype != "exo")
129 {
130 h_endo = ifelse(simtype=="mix", h[1], h)
9db234c5 131
5e838b3e
BA
132 # Distances from last observed day to days in the past
133 serieToday = data$getSerie(today)
6774e53d 134 distances2 = sapply(fdays, function(i) {
5e838b3e
BA
135 delta = serieToday - data$getSerie(i)
136 mean(delta^2)
137 })
5c49f6ce 138
5e838b3e
BA
139 sd_dist = sd(distances2)
140 if (sd_dist < .Machine$double.eps)
141 {
5c49f6ce 142# warning("All computed distances are very close: stdev too small")
5e838b3e
BA
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 }
5c49f6ce 155 }
5e838b3e
BA
156
157 if (simtype != "endo")
158 {
159 h_exo = ifelse(simtype=="mix", h[2], h)
160
6774e53d 161 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
5e838b3e 162 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
6774e53d
BA
163 for (i in seq_along(fdays))
164 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
5e838b3e
BA
165
166 sigma = cov(M) #NOTE: robust covariance is way too slow
ee8b1b4e
BA
167 # TODO: 10 == magic number; more robust way == det, or always ginv()
168 sigma_inv =
6774e53d 169 if (length(fdays) > 10)
ee8b1b4e
BA
170 solve(sigma)
171 else
172 MASS::ginv(sigma)
a866acb3 173
5e838b3e 174 # Distances from last observed day to days in the past
6774e53d 175 distances2 = sapply(seq_along(fdays), function(i) {
5e838b3e
BA
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))
5c49f6ce 182 {
5e838b3e
BA
183# warning("All computed distances are very close: stdev too small")
184 sd_dist = 1 #mostly for tests... FIXME:
5c49f6ce 185 }
5e838b3e
BA
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 }
5c49f6ce 197
5e838b3e
BA
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
ea5c7e56 205 similarities = similarities / sum(similarities)
5c49f6ce
BA
206
207 prediction = rep(0, horizon)
6774e53d 208 for (i in seq_along(fdays))
9003747b 209 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
5c49f6ce
BA
210
211 if (final_call)
212 {
9003747b 213 prediction = prediction - mean(prediction) #predict centered serie (artificial...)
5c49f6ce 214 private$.params$weights <- similarities
6774e53d 215 private$.params$indices <- fdays
5e838b3e
BA
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)
5c49f6ce
BA
223 }
224
225 return (prediction)
226 }
227 )
228)