1 #' @include Forecaster.R
3 #' @title Neighbors Forecaster
5 #' @description Predict tomorrow as a weighted combination of "futures of the past" days.
6 #' Inherits \code{\link{Forecaster}}
7 NeighborsForecaster = setRefClass(
8 Class = "NeighborsForecaster",
9 contains = "Forecaster",
12 initialize = function(...)
16 predictShape = function(today, memory, horizon, ...)
18 # (re)initialize computed parameters
19 params <<- list("weights"=NA, "indices"=NA, "window"=NA)
22 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
23 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
25 return (.predictShapeAux(fdays,today,horizon,list(...)$h_window,kernel,simtype,TRUE))
27 # HACK for test reports: complete some days with a few NAs, for nicer graphics
28 nas_in_serie = is.na(data$getSerie(today))
29 if (any(nas_in_serie))
31 if (sum(nas_in_serie) >= length(nas_in_serie) / 2)
33 for (i in seq_along(nas_in_serie))
39 while (left>=1 && nas_in_serie[left])
43 while (right<=length(nas_in_serie) && nas_in_serie[right])
45 #HACK: modify by-reference Data object...
46 data$data[[today]]$serie[i] <<-
47 if (left==0) data$data[[today]]$serie[right]
48 else if (right==0) data$data[[today]]$serie[left]
49 else (data$data[[today]]$serie[left] + data$data[[today]]$serie[right]) / 2.
54 # Determine indices of no-NAs days followed by no-NAs tomorrows
55 first_day = max(today - memory, 1)
56 fdays = (first_day:(today-1))[ sapply(first_day:(today-1), function(i) {
57 !any(is.na(data$getSerie(i)) | is.na(data$getSerie(i+1)))
60 # Indices of similar days for cross-validation; TODO: 45 = magic number
61 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
63 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
64 errorOnLastNdays = function(h, kernel, simtype)
68 for (i in intersect(fdays,sdays))
70 # mix_strategy is never used here (simtype != "mix"), therefore left blank
71 prediction = .predictShapeAux(fdays, i, horizon, h, kernel, simtype, FALSE)
72 if (!is.na(prediction[1]))
74 nb_jours = nb_jours + 1
75 error = error + mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
78 return (error / nb_jours)
81 if (simtype != "endo")
82 h_best_exo = optimize(errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
84 h_best_endo = optimize(errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
86 if (simtype == "endo")
87 return (.predictShapeAux(fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
89 return (.predictShapeAux(fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
92 h_best_mix = c(h_best_endo,h_best_exo)
93 return (.predictShapeAux(fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
96 # Precondition: "today" is full (no NAs)
97 .predictShapeAux = function(fdays, today, horizon, h, kernel, simtype, final_call)
99 dat = data$data #HACK: faster this way...
101 fdays = fdays[ fdays < today ]
102 # TODO: 3 = magic number
103 if (length(fdays) < 3)
106 if (simtype != "exo")
108 h_endo = ifelse(simtype=="mix", h[1], h)
110 # Distances from last observed day to days in the past
111 distances2 = rep(NA, length(fdays))
112 for (i in seq_along(fdays))
114 delta = dat[[today]]$serie - dat[[ fdays[i] ]]$serie
115 # Require at least half of non-NA common values to compute the distance
116 if (sum(is.na(delta)) <= 0) #length(delta)/2)
117 distances2[i] = mean(delta^2) #, na.rm=TRUE)
120 sd_dist = sd(distances2)
121 if (sd_dist < .Machine$double.eps)
122 sd_dist = 1 #mostly for tests... FIXME:
125 exp(-distances2/(sd_dist*h_endo^2))
127 u = 1 - distances2/(sd_dist*h_endo^2)
133 if (simtype != "endo")
135 h_exo = ifelse(simtype=="mix", h[2], h)
137 M = matrix( nrow=1+length(fdays), ncol=1+length(dat[[today]]$exo) )
138 M[1,] = c( dat[[today]]$level, as.double(dat[[today]]$exo) )
139 for (i in seq_along(fdays))
140 M[i+1,] = c( dat[[ fdays[i] ]]$level, as.double(dat[[ fdays[i] ]]$exo) )
142 sigma = cov(M) #NOTE: robust covariance is way too slow
143 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
145 # Distances from last observed day to days in the past
146 distances2 = rep(NA, nrow(M)-1)
149 delta = M[1,] - M[i,]
150 distances2[i-1] = delta %*% sigma_inv %*% delta
153 sd_dist = sd(distances2)
156 exp(-distances2/(sd_dist*h_exo^2))
158 u = 1 - distances2/(sd_dist*h_exo^2)
165 if (simtype == "exo")
167 else if (simtype == "endo")
170 simils_endo * simils_exo
172 prediction = rep(0, horizon)
173 for (i in seq_along(fdays_indices))
174 prediction = prediction + similarities[i] * dat[[ fdays_indices[i]+1 ]]$serie[1:horizon]
175 prediction = prediction / sum(similarities, na.rm=TRUE)
179 params$weights <<- similarities
180 params$indices <<- fdays_indices
182 if (simtype=="endo") {
184 } else if (simtype=="exo") {