fix window bounds
[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
BA
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))
a66a84b5 28 {
98e958ca 29 return ( private$.predictShapeAux(data,
a66a84b5
BA
30 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
31 }
3d69ff21 32
6774e53d
BA
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)
5e838b3e 35
3d69ff21
BA
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
5e838b3e 41 for (i in seq_along(cv_days))
3d69ff21 42 {
f17665c7 43 # mix_strategy is never used here (simtype != "mix"), therefore left blank
98e958ca 44 prediction = private$.predictShapeAux(data,
5e838b3e 45 fdays, cv_days[i], horizon, h, kernel, simtype, FALSE)
f17665c7 46 if (!is.na(prediction[1]))
3d69ff21
BA
47 {
48 nb_jours = nb_jours + 1
af3b84f4 49 error = error +
5e838b3e 50 mean((data$getCenteredSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
3d69ff21
BA
51 }
52 }
53 return (error / nb_jours)
54 }
55
f17665c7 56 if (simtype != "endo")
af3b84f4
BA
57 {
58 h_best_exo = optimize(
ea5c7e56 59 errorOnLastNdays, c(0,7), kernel=kernel, simtype="exo")$minimum
af3b84f4 60 }
3d69ff21 61 if (simtype != "exo")
af3b84f4
BA
62 {
63 h_best_endo = optimize(
ea5c7e56 64 errorOnLastNdays, c(0,7), kernel=kernel, simtype="endo")$minimum
af3b84f4 65 }
3d69ff21
BA
66
67 if (simtype == "endo")
af3b84f4 68 {
98e958ca 69 return (private$.predictShapeAux(data,
af3b84f4
BA
70 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
71 }
3d69ff21 72 if (simtype == "exo")
af3b84f4 73 {
98e958ca 74 return (private$.predictShapeAux(data,
af3b84f4
BA
75 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
76 }
3d69ff21
BA
77 if (simtype == "mix")
78 {
f17665c7 79 h_best_mix = c(h_best_endo,h_best_exo)
98e958ca 80 return(private$.predictShapeAux(data,
af3b84f4 81 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
3d69ff21 82 }
25b75559
BA
83 }
84 ),
85 private = list(
3d69ff21 86 # Precondition: "today" is full (no NAs)
98e958ca 87 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
3d69ff21 88 {
f17665c7 89 fdays = fdays[ fdays < today ]
3d69ff21 90 # TODO: 3 = magic number
f17665c7 91 if (length(fdays) < 3)
3d69ff21
BA
92 return (NA)
93
94 if (simtype != "exo")
95 {
96 h_endo = ifelse(simtype=="mix", h[1], h)
97
98 # Distances from last observed day to days in the past
5e838b3e
BA
99 serieToday = data$getSerie(today)
100 distances2 = sapply(fdays, function(i) {
101 delta = serieToday - data$getSerie(i)
102 mean(delta^2)
103 })
3d69ff21
BA
104
105 sd_dist = sd(distances2)
99f83c9a 106 if (sd_dist < .Machine$double.eps)
546b0cb6 107 {
fa5b7bfc 108# warning("All computed distances are very close: stdev too small")
99f83c9a 109 sd_dist = 1 #mostly for tests... FIXME:
546b0cb6 110 }
3d69ff21 111 simils_endo =
99f83c9a 112 if (kernel=="Gauss")
3d69ff21 113 exp(-distances2/(sd_dist*h_endo^2))
546b0cb6
BA
114 else
115 {
116 # Epanechnikov
3d69ff21
BA
117 u = 1 - distances2/(sd_dist*h_endo^2)
118 u[abs(u)>1] = 0.
119 u
120 }
121 }
122
123 if (simtype != "endo")
124 {
125 h_exo = ifelse(simtype=="mix", h[2], h)
126
25b75559
BA
127 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
128 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
f17665c7 129 for (i in seq_along(fdays))
25b75559 130 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
3d69ff21
BA
131
132 sigma = cov(M) #NOTE: robust covariance is way too slow
ee8b1b4e
BA
133 # TODO: 10 == magic number; more robust way == det, or always ginv()
134 sigma_inv =
135 if (length(fdays) > 10)
136 solve(sigma)
137 else
138 MASS::ginv(sigma)
3d69ff21
BA
139
140 # Distances from last observed day to days in the past
5e838b3e
BA
141 distances2 = sapply(seq_along(fdays), function(i) {
142 delta = M[1,] - M[i+1,]
143 delta %*% sigma_inv %*% delta
144 })
3d69ff21
BA
145
146 sd_dist = sd(distances2)
ee8b1b4e 147 if (sd_dist < .25 * sqrt(.Machine$double.eps))
546b0cb6 148 {
fa5b7bfc 149# warning("All computed distances are very close: stdev too small")
546b0cb6
BA
150 sd_dist = 1 #mostly for tests... FIXME:
151 }
3d69ff21 152 simils_exo =
f17665c7 153 if (kernel=="Gauss")
3d69ff21 154 exp(-distances2/(sd_dist*h_exo^2))
546b0cb6
BA
155 else
156 {
157 # Epanechnikov
3d69ff21
BA
158 u = 1 - distances2/(sd_dist*h_exo^2)
159 u[abs(u)>1] = 0.
160 u
161 }
162 }
163
3d69ff21 164 similarities =
f17665c7 165 if (simtype == "exo")
3d69ff21 166 simils_exo
f17665c7
BA
167 else if (simtype == "endo")
168 simils_endo
169 else #mix
170 simils_endo * simils_exo
ea5c7e56 171 similarities = similarities / sum(similarities)
3d69ff21
BA
172
173 prediction = rep(0, horizon)
a66a84b5 174 for (i in seq_along(fdays))
5c49f6ce 175 prediction = prediction + similarities[i] * data$getCenteredSerie(fdays[i]+1)[1:horizon]
99f83c9a 176
3d69ff21
BA
177 if (final_call)
178 {
a66a84b5
BA
179 private$.params$weights <- similarities
180 private$.params$indices <- fdays
181 private$.params$window <-
546b0cb6 182 if (simtype=="endo")
3d69ff21 183 h_endo
546b0cb6 184 else if (simtype=="exo")
3d69ff21 185 h_exo
546b0cb6 186 else #mix
3d69ff21 187 c(h_endo,h_exo)
3d69ff21 188 }
99f83c9a 189
3d69ff21
BA
190 return (prediction)
191 }
192 )
193)