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