1 #' @include Forecaster.R
3 #' Neighbors2 Forecaster
5 #' Predict tomorrow as a weighted combination of "futures of the past" days.
6 #' Inherits \code{\link{Forecaster}}
8 Neighbors2Forecaster = R6::R6Class("Neighbors2Forecaster",
12 predictSerie = function(data, today, memory, horizon, ...)
14 # Parameters (potentially) computed during shape prediction stage
15 predicted_shape = self$predictShape(data, today, memory, horizon, ...)
16 # predicted_delta = private$.pjump(data,today,memory,horizon,private$.params,...)
17 # Predicted shape is aligned it on the end of current day + jump
18 # predicted_shape+tail(data$getSerie(today),1)-predicted_shape[1]+predicted_delta
21 predictShape = function(data, today, memory, horizon, ...)
23 # (re)initialize computed parameters
24 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
26 # Do not forecast on days with NAs (TODO: softer condition...)
27 if (any(is.na(data$getCenteredSerie(today))))
30 # Determine indices of no-NAs days followed by no-NAs tomorrows
31 fdays = getNoNA2(data, max(today-memory,1), today-1)
34 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
35 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
38 return ( private$.predictShapeAux(data,
39 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
42 # Indices of similar days for cross-validation; TODO: 45 = magic number
43 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
45 cv_days = intersect(fdays,sdays)
46 # Limit to 20 most recent matching days (TODO: 20 == magic number)
47 cv_days = sort(cv_days,decreasing=TRUE)[1:min(20,length(cv_days))]
49 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
50 errorOnLastNdays = function(h, kernel, simtype)
54 for (i in seq_along(cv_days))
56 # mix_strategy is never used here (simtype != "mix"), therefore left blank
57 prediction = private$.predictShapeAux(data,
58 fdays, cv_days[i], horizon, h, kernel, simtype, FALSE)
59 if (!is.na(prediction[1]))
61 nb_jours = nb_jours + 1
63 mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
66 return (error / nb_jours)
69 if (simtype != "endo")
71 h_best_exo = optimize(
72 errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
76 h_best_endo = optimize(
77 errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
80 if (simtype == "endo")
82 return (private$.predictShapeAux(data,
83 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
87 return (private$.predictShapeAux(data,
88 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
92 h_best_mix = c(h_best_endo,h_best_exo)
93 return(private$.predictShapeAux(data,
94 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
99 # Precondition: "today" is full (no NAs)
100 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
102 fdays = fdays[ fdays < today ]
103 # TODO: 3 = magic number
104 if (length(fdays) < 3)
107 # Neighbors: days in "same season"
108 sdays = getSimilarDaysIndices(today, limit=45, same_season=TRUE, data)
109 indices = intersect(fdays,sdays)
110 levelToday = data$getLevel(today)
111 distances = sapply(indices, function(i) abs(data$getLevel(i)-levelToday))
112 same_pollution = (distances <= 2)
113 if (sum(same_pollution) < 3) #TODO: 3 == magic number
115 same_pollution = (distances <= 5)
116 if (sum(same_pollution) < 3)
119 indices = indices[same_pollution]
121 if (simtype != "exo")
123 h_endo = ifelse(simtype=="mix", h[1], h)
125 # Distances from last observed day to days in the past
126 serieToday = data$getSerie(today)
127 distances2 = sapply(indices, function(i) {
128 delta = serieToday - data$getSerie(i)
132 sd_dist = sd(distances2)
133 if (sd_dist < .Machine$double.eps)
135 # warning("All computed distances are very close: stdev too small")
136 sd_dist = 1 #mostly for tests... FIXME:
140 exp(-distances2/(sd_dist*h_endo^2))
144 u = 1 - distances2/(sd_dist*h_endo^2)
150 if (simtype != "endo")
152 h_exo = ifelse(simtype=="mix", h[2], h)
154 M = matrix( nrow=1+length(indices), ncol=1+length(data$getExo(today)) )
155 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
156 for (i in seq_along(indices))
157 M[i+1,] = c( data$getLevel(indices[i]), as.double(data$getExo(indices[i])) )
159 sigma = cov(M) #NOTE: robust covariance is way too slow
160 # sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
161 sigma_inv = MASS::ginv(sigma)
162 #if (final_call) browser()
163 # Distances from last observed day to days in the past
164 distances2 = sapply(seq_along(indices), function(i) {
165 delta = M[1,] - M[i+1,]
166 delta %*% sigma_inv %*% delta
169 sd_dist = sd(distances2)
170 if (sd_dist < .25 * sqrt(.Machine$double.eps))
172 # warning("All computed distances are very close: stdev too small")
173 sd_dist = 1 #mostly for tests... FIXME:
177 exp(-distances2/(sd_dist*h_exo^2))
181 u = 1 - distances2/(sd_dist*h_exo^2)
188 if (simtype == "exo")
190 else if (simtype == "endo")
193 simils_endo * simils_exo
195 prediction = rep(0, horizon)
196 for (i in seq_along(indices))
197 prediction = prediction + similarities[i] * data$getSerie(indices[i]+1)[1:horizon]
198 prediction = prediction / sum(similarities, na.rm=TRUE)
202 private$.params$weights <- similarities
203 private$.params$indices <- fdays
204 private$.params$window <-
207 else if (simtype=="exo")