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