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