first tests for Neighbors2 after debug; TODO: some missing forecasts
[talweg.git] / pkg / R / F_Neighbors.R
... / ...
CommitLineData
1#' @include Forecaster.R
2#'
3#' Neighbors Forecaster
4#'
5#' Predict tomorrow as a weighted combination of "futures of the past" days.
6#' Inherits \code{\link{Forecaster}}
7#'
8NeighborsForecaster = R6::R6Class("NeighborsForecaster",
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: 45 = magic number
34 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
35
36 cv_days = intersect(fdays,sdays)
37 # Limit to 20 most recent matching days (TODO: 20 == magic number)
38 cv_days = sort(cv_days,decreasing=TRUE)[1:min(20,length(cv_days))]
39
40 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
41 errorOnLastNdays = function(h, kernel, simtype)
42 {
43 error = 0
44 nb_jours = 0
45 for (i in seq_along(cv_days))
46 {
47 # mix_strategy is never used here (simtype != "mix"), therefore left blank
48 prediction = private$.predictShapeAux(data,
49 fdays, cv_days[i], horizon, h, kernel, simtype, FALSE)
50 if (!is.na(prediction[1]))
51 {
52 nb_jours = nb_jours + 1
53 error = error +
54 mean((data$getCenteredSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
55 }
56 }
57 return (error / nb_jours)
58 }
59
60 if (simtype != "endo")
61 {
62 h_best_exo = optimize(
63 errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
64 }
65 if (simtype != "exo")
66 {
67 h_best_endo = optimize(
68 errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
69 }
70
71 if (simtype == "endo")
72 {
73 return (private$.predictShapeAux(data,
74 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
75 }
76 if (simtype == "exo")
77 {
78 return (private$.predictShapeAux(data,
79 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
80 }
81 if (simtype == "mix")
82 {
83 h_best_mix = c(h_best_endo,h_best_exo)
84 return(private$.predictShapeAux(data,
85 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
86 }
87 }
88 ),
89 private = list(
90 # Precondition: "today" is full (no NAs)
91 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
92 {
93 fdays = fdays[ fdays < today ]
94 # TODO: 3 = magic number
95 if (length(fdays) < 3)
96 return (NA)
97
98 if (simtype != "exo")
99 {
100 h_endo = ifelse(simtype=="mix", h[1], h)
101
102 # Distances from last observed day to days in the past
103 serieToday = data$getSerie(today)
104 distances2 = sapply(fdays, function(i) {
105 delta = serieToday - data$getSerie(i)
106 mean(delta^2)
107 })
108
109 sd_dist = sd(distances2)
110 if (sd_dist < .Machine$double.eps)
111 {
112# warning("All computed distances are very close: stdev too small")
113 sd_dist = 1 #mostly for tests... FIXME:
114 }
115 simils_endo =
116 if (kernel=="Gauss")
117 exp(-distances2/(sd_dist*h_endo^2))
118 else
119 {
120 # Epanechnikov
121 u = 1 - distances2/(sd_dist*h_endo^2)
122 u[abs(u)>1] = 0.
123 u
124 }
125 }
126
127 if (simtype != "endo")
128 {
129 h_exo = ifelse(simtype=="mix", h[2], h)
130
131 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
132 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
133 for (i in seq_along(fdays))
134 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
135
136 sigma = cov(M) #NOTE: robust covariance is way too slow
137 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
138
139 # Distances from last observed day to days in the past
140 distances2 = sapply(seq_along(fdays), function(i) {
141 delta = M[1,] - M[i+1,]
142 delta %*% sigma_inv %*% delta
143 })
144
145 sd_dist = sd(distances2)
146 if (sd_dist < .Machine$double.eps)
147 {
148# warning("All computed distances are very close: stdev too small")
149 sd_dist = 1 #mostly for tests... FIXME:
150 }
151 simils_exo =
152 if (kernel=="Gauss")
153 exp(-distances2/(sd_dist*h_exo^2))
154 else
155 {
156 # Epanechnikov
157 u = 1 - distances2/(sd_dist*h_exo^2)
158 u[abs(u)>1] = 0.
159 u
160 }
161 }
162
163 similarities =
164 if (simtype == "exo")
165 simils_exo
166 else if (simtype == "endo")
167 simils_endo
168 else #mix
169 simils_endo * simils_exo
170
171 prediction = rep(0, horizon)
172 for (i in seq_along(fdays))
173 prediction = prediction + similarities[i] * data$getCenteredSerie(fdays[i]+1)[1:horizon]
174 prediction = prediction / sum(similarities, na.rm=TRUE)
175
176 if (final_call)
177 {
178 private$.params$weights <- similarities
179 private$.params$indices <- fdays
180 private$.params$window <-
181 if (simtype=="endo")
182 h_endo
183 else if (simtype=="exo")
184 h_exo
185 else #mix
186 c(h_endo,h_exo)
187 }
188
189 return (prediction)
190 }
191 )
192)