69e69dcca8e1c8a6938b97d410013401f922ae63
[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 +
50 mean((data$getCenteredSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
51 }
52 }
53 return (error / nb_jours)
54 }
55
56 if (simtype != "endo")
57 {
58 h_best_exo = optimize(
59 errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
60 }
61 if (simtype != "exo")
62 {
63 h_best_endo = optimize(
64 errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
65 }
66
67 if (simtype == "endo")
68 {
69 return (private$.predictShapeAux(data,
70 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
71 }
72 if (simtype == "exo")
73 {
74 return (private$.predictShapeAux(data,
75 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
76 }
77 if (simtype == "mix")
78 {
79 h_best_mix = c(h_best_endo,h_best_exo)
80 return(private$.predictShapeAux(data,
81 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
82 }
83 }
84 ),
85 private = list(
86 # Precondition: "today" is full (no NAs)
87 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
88 {
89 fdays_cut = fdays[ fdays < today ]
90 # TODO: 3 = magic number
91 if (length(fdays_cut) < 3)
92 return (NA)
93
94 # Neighbors: days in "same season"; TODO: 60 == magic number...
95 fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE, days_in=fdays_cut)
96 if (length(fdays) <= 1)
97 return (NA)
98 levelToday = data$getLevel(today)
99 distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
100 dist_thresh = 1
101 repeat
102 {
103 same_pollution = (distances <= dist_thresh)
104 if (sum(same_pollution) >= 2) #will eventually happen
105 break
106 dist_thresh = dist_thresh + 1
107 }
108 fdays = fdays[same_pollution]
109 if (length(fdays) == 1)
110 {
111 if (final_call)
112 {
113 private$.params$weights <- 1
114 private$.params$indices <- fdays
115 private$.params$window <- 1
116 }
117 return ( data$getSerie(fdays[1])[1:horizon] ) #what else?!
118 }
119
120 if (simtype != "exo")
121 {
122 h_endo = ifelse(simtype=="mix", h[1], h)
123
124 # Distances from last observed day to days in the past
125 serieToday = data$getSerie(today)
126 distances2 = sapply(fdays, function(i) {
127 delta = serieToday - data$getSerie(i)
128 mean(delta^2)
129 })
130
131 sd_dist = sd(distances2)
132 if (sd_dist < .Machine$double.eps)
133 {
134 # warning("All computed distances are very close: stdev too small")
135 sd_dist = 1 #mostly for tests... FIXME:
136 }
137 simils_endo =
138 if (kernel=="Gauss")
139 exp(-distances2/(sd_dist*h_endo^2))
140 else
141 {
142 # Epanechnikov
143 u = 1 - distances2/(sd_dist*h_endo^2)
144 u[abs(u)>1] = 0.
145 u
146 }
147 }
148
149 if (simtype != "endo")
150 {
151 h_exo = ifelse(simtype=="mix", h[2], h)
152
153 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
154 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
155 for (i in seq_along(fdays))
156 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
157
158 sigma = cov(M) #NOTE: robust covariance is way too slow
159 # TODO: 10 == magic number; more robust way == det, or always ginv()
160 sigma_inv =
161 if (length(fdays) > 10)
162 solve(sigma)
163 else
164 MASS::ginv(sigma)
165
166 # Distances from last observed day to days in the past
167 distances2 = sapply(seq_along(fdays), function(i) {
168 delta = M[1,] - M[i+1,]
169 delta %*% sigma_inv %*% delta
170 })
171
172 sd_dist = sd(distances2)
173 if (sd_dist < .25 * sqrt(.Machine$double.eps))
174 {
175 # warning("All computed distances are very close: stdev too small")
176 sd_dist = 1 #mostly for tests... FIXME:
177 }
178 simils_exo =
179 if (kernel=="Gauss")
180 exp(-distances2/(sd_dist*h_exo^2))
181 else
182 {
183 # Epanechnikov
184 u = 1 - distances2/(sd_dist*h_exo^2)
185 u[abs(u)>1] = 0.
186 u
187 }
188 }
189
190 similarities =
191 if (simtype == "exo")
192 simils_exo
193 else if (simtype == "endo")
194 simils_endo
195 else #mix
196 simils_endo * simils_exo
197
198 prediction = rep(0, horizon)
199 for (i in seq_along(fdays))
200 prediction = prediction + similarities[i] * data$getCenteredSerie(fdays[i]+1)[1:horizon]
201 prediction = prediction / sum(similarities, na.rm=TRUE)
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 h_endo
210 else if (simtype=="exo")
211 h_exo
212 else #mix
213 c(h_endo,h_exo)
214 }
215
216 return (prediction)
217 }
218 )
219 )