on the way back without realtime
[talweg.git] / pkg / R / F_Neighbors.R
CommitLineData
25b75559 1#' Neighbors Forecaster
3d69ff21 2#'
25b75559
BA
3#' Predict tomorrow as a weighted combination of "futures of the past" days.
4#' Inherits \code{\link{Forecaster}}
546b0cb6 5#'
25b75559 6NeighborsForecaster = R6::R6Class("NeighborsForecaster",
a66a84b5 7 inherit = Forecaster,
25b75559
BA
8
9 public = list(
98e958ca 10 predictShape = function(data, today, memory, horizon, ...)
3d69ff21
BA
11 {
12 # (re)initialize computed parameters
a66a84b5 13 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
3d69ff21 14
a5a3a294
BA
15 # Do not forecast on days with NAs (TODO: softer condition...)
16 if (any(is.na(data$getCenteredSerie(today))))
17 return (NA)
18
af3b84f4 19 # Determine indices of no-NAs days followed by no-NAs tomorrows
98e958ca 20 fdays = getNoNA2(data, max(today-memory,1), today-1)
af3b84f4 21
f17665c7 22 # Get optional args
445e7bbc
BA
23 local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
24 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
aa059de7 25 if (hasArg("window"))
a66a84b5 26 {
98e958ca 27 return ( private$.predictShapeAux(data,
aa059de7 28 fdays, today, horizon, local, list(...)$window, simtype, TRUE) )
a66a84b5 29 }
3d69ff21 30
6774e53d 31 # Indices of similar days for cross-validation; TODO: 20 = magic number
aa059de7
BA
32 cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE,
33 days_in=fdays)
5e838b3e 34
445e7bbc 35 # Optimize h : h |--> sum of prediction errors on last N "similar" days
aa059de7 36 errorOnLastNdays = function(window, simtype)
3d69ff21
BA
37 {
38 error = 0
39 nb_jours = 0
5e838b3e 40 for (i in seq_along(cv_days))
3d69ff21 41 {
f17665c7 42 # mix_strategy is never used here (simtype != "mix"), therefore left blank
aa059de7
BA
43 prediction = private$.predictShapeAux(data, fdays, cv_days[i], horizon, local,
44 window, simtype, FALSE)
f17665c7 45 if (!is.na(prediction[1]))
3d69ff21
BA
46 {
47 nb_jours = nb_jours + 1
af3b84f4 48 error = error +
aa059de7 49 mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
3d69ff21
BA
50 }
51 }
52 return (error / nb_jours)
53 }
54
445e7bbc 55 # TODO: 7 == magic number
eef54517 56 if (simtype=="endo" || simtype=="mix")
af3b84f4 57 {
aa059de7
BA
58 best_window_endo = optimize(
59 errorOnLastNdays, c(0,7), simtype="endo")$minimum
af3b84f4 60 }
eef54517 61 if (simtype=="exo" || simtype=="mix")
af3b84f4 62 {
eef54517
BA
63 best_window_exo = optimize(
64 errorOnLastNdays, c(0,7), simtype="exo")$minimum
3d69ff21 65 }
eef54517
BA
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))
25b75559
BA
79 }
80 ),
81 private = list(
3d69ff21 82 # Precondition: "today" is full (no NAs)
aa059de7
BA
83 .predictShapeAux = function(data, fdays, today, horizon, local, window, simtype,
84 final_call)
3d69ff21 85 {
aa059de7
BA
86 fdays_cut = fdays[ fdays < today ]
87 if (length(fdays_cut) <= 1)
3d69ff21
BA
88 return (NA)
89
aa059de7
BA
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))
445e7bbc 99 #TODO: 2, 10, 3, 12 magic numbers here...
aa059de7 100 dist_thresh = 2
445e7bbc 101 min_neighbs = min(10,length(fdays))
aa059de7
BA
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]
445e7bbc 111 max_neighbs = 12
aa059de7
BA
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 }
2057c793 126 return ( data$getSerie(fdays[1])[1:horizon] )
aa059de7
BA
127 }
128 }
129 else
130 fdays = fdays_cut #no conditioning
131
445e7bbc 132 if (simtype == "endo" || simtype == "mix")
3d69ff21 133 {
aa059de7
BA
134 # Compute endogen similarities using given window
135 window_endo = ifelse(simtype=="mix", window[1], window)
3d69ff21
BA
136
137 # Distances from last observed day to days in the past
5e838b3e
BA
138 serieToday = data$getSerie(today)
139 distances2 = sapply(fdays, function(i) {
140 delta = serieToday - data$getSerie(i)
141 mean(delta^2)
142 })
3d69ff21
BA
143
144 sd_dist = sd(distances2)
aa059de7 145 if (sd_dist < .25 * sqrt(.Machine$double.eps))
546b0cb6 146 {
fa5b7bfc 147# warning("All computed distances are very close: stdev too small")
99f83c9a 148 sd_dist = 1 #mostly for tests... FIXME:
546b0cb6 149 }
aa059de7 150 simils_endo = exp(-distances2/(sd_dist*window_endo^2))
3d69ff21
BA
151 }
152
445e7bbc 153 if (simtype == "exo" || simtype == "mix")
3d69ff21 154 {
aa059de7 155 # Compute exogen similarities using given window
445e7bbc 156 window_exo = ifelse(simtype=="mix", window[2], window)
3d69ff21 157
25b75559
BA
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)) )
f17665c7 160 for (i in seq_along(fdays))
25b75559 161 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
3d69ff21
BA
162
163 sigma = cov(M) #NOTE: robust covariance is way too slow
ee8b1b4e
BA
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)
3d69ff21
BA
170
171 # Distances from last observed day to days in the past
5e838b3e
BA
172 distances2 = sapply(seq_along(fdays), function(i) {
173 delta = M[1,] - M[i+1,]
174 delta %*% sigma_inv %*% delta
175 })
3d69ff21
BA
176
177 sd_dist = sd(distances2)
ee8b1b4e 178 if (sd_dist < .25 * sqrt(.Machine$double.eps))
546b0cb6 179 {
fa5b7bfc 180# warning("All computed distances are very close: stdev too small")
546b0cb6
BA
181 sd_dist = 1 #mostly for tests... FIXME:
182 }
aa059de7 183 simils_exo = exp(-distances2/(sd_dist*window_exo^2))
3d69ff21
BA
184 }
185
3d69ff21 186 similarities =
f17665c7 187 if (simtype == "exo")
3d69ff21 188 simils_exo
f17665c7
BA
189 else if (simtype == "endo")
190 simils_endo
445e7bbc 191 else if (simtype == "mix")
f17665c7 192 simils_endo * simils_exo
445e7bbc
BA
193 else #none
194 rep(1, length(fdays))
ea5c7e56 195 similarities = similarities / sum(similarities)
3d69ff21
BA
196
197 prediction = rep(0, horizon)
a66a84b5 198 for (i in seq_along(fdays))
aa059de7 199 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
99f83c9a 200
3d69ff21
BA
201 if (final_call)
202 {
a66a84b5
BA
203 private$.params$weights <- similarities
204 private$.params$indices <- fdays
205 private$.params$window <-
546b0cb6 206 if (simtype=="endo")
aa059de7 207 window_endo
546b0cb6 208 else if (simtype=="exo")
aa059de7 209 window_exo
eef54517 210 else if (simtype=="mix")
aa059de7 211 c(window_endo,window_exo)
eef54517
BA
212 else #none
213 1
3d69ff21 214 }
99f83c9a 215
3d69ff21
BA
216 return (prediction)
217 }
218 )
219)