on the way to R6 class + remove truncated days (simplifications)
[talweg.git] / pkg / R / F_Neighbors.R
CommitLineData
e030a6e3 1#' @include Forecaster.R
3d69ff21 2#'
e030a6e3 3#' @title Neighbors Forecaster
3d69ff21
BA
4#'
5#' @description Predict tomorrow as a weighted combination of "futures of the past" days.
e030a6e3
BA
6#' Inherits \code{\link{Forecaster}}
7NeighborsForecaster = setRefClass(
8 Class = "NeighborsForecaster",
9 contains = "Forecaster",
3d69ff21
BA
10
11 methods = list(
12 initialize = function(...)
13 {
14 callSuper(...)
15 },
e030a6e3 16 predictShape = function(today, memory, horizon, ...)
3d69ff21
BA
17 {
18 # (re)initialize computed parameters
19 params <<- list("weights"=NA, "indices"=NA, "window"=NA)
20
f17665c7
BA
21 # Get optional args
22 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
23 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
24 if (hasArg(h_window))
25 return (.predictShapeAux(fdays,today,horizon,list(...)$h_window,kernel,simtype,TRUE))
3d69ff21 26
f17665c7 27 # HACK for test reports: complete some days with a few NAs, for nicer graphics
09cf9c19
BA
28 nas_in_serie = is.na(data$getSerie(today))
29 if (any(nas_in_serie))
30 {
09cf9c19
BA
31 if (sum(nas_in_serie) >= length(nas_in_serie) / 2)
32 return (NA)
33 for (i in seq_along(nas_in_serie))
34 {
35 if (nas_in_serie[i])
36 {
37 #look left
38 left = i-1
39 while (left>=1 && nas_in_serie[left])
40 left = left-1
41 #look right
42 right = i+1
43 while (right<=length(nas_in_serie) && nas_in_serie[right])
44 right = right+1
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.
50 }
51 }
52 }
3d69ff21
BA
53
54 # Determine indices of no-NAs days followed by no-NAs tomorrows
f17665c7
BA
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)))
58 }) ]
3d69ff21 59
f17665c7
BA
60 # Indices of similar days for cross-validation; TODO: 45 = magic number
61 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
3d69ff21
BA
62
63 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
64 errorOnLastNdays = function(h, kernel, simtype)
65 {
66 error = 0
67 nb_jours = 0
f17665c7 68 for (i in intersect(fdays,sdays))
3d69ff21 69 {
f17665c7
BA
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]))
3d69ff21
BA
73 {
74 nb_jours = nb_jours + 1
f17665c7 75 error = error + mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
3d69ff21
BA
76 }
77 }
78 return (error / nb_jours)
79 }
80
f17665c7
BA
81 if (simtype != "endo")
82 h_best_exo = optimize(errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
3d69ff21 83 if (simtype != "exo")
f17665c7 84 h_best_endo = optimize(errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
3d69ff21
BA
85
86 if (simtype == "endo")
f17665c7 87 return (.predictShapeAux(fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
3d69ff21 88 if (simtype == "exo")
f17665c7 89 return (.predictShapeAux(fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
3d69ff21
BA
90 if (simtype == "mix")
91 {
f17665c7
BA
92 h_best_mix = c(h_best_endo,h_best_exo)
93 return (.predictShapeAux(fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
3d69ff21
BA
94 }
95 },
96 # Precondition: "today" is full (no NAs)
f17665c7 97 .predictShapeAux = function(fdays, today, horizon, h, kernel, simtype, final_call)
3d69ff21
BA
98 {
99 dat = data$data #HACK: faster this way...
100
f17665c7 101 fdays = fdays[ fdays < today ]
3d69ff21 102 # TODO: 3 = magic number
f17665c7 103 if (length(fdays) < 3)
3d69ff21
BA
104 return (NA)
105
106 if (simtype != "exo")
107 {
108 h_endo = ifelse(simtype=="mix", h[1], h)
109
110 # Distances from last observed day to days in the past
f17665c7
BA
111 distances2 = rep(NA, length(fdays))
112 for (i in seq_along(fdays))
3d69ff21 113 {
f17665c7 114 delta = dat[[today]]$serie - dat[[ fdays[i] ]]$serie
3d69ff21
BA
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)
118 }
119
120 sd_dist = sd(distances2)
99f83c9a
BA
121 if (sd_dist < .Machine$double.eps)
122 sd_dist = 1 #mostly for tests... FIXME:
3d69ff21 123 simils_endo =
99f83c9a 124 if (kernel=="Gauss")
3d69ff21 125 exp(-distances2/(sd_dist*h_endo^2))
99f83c9a 126 else { #Epanechnikov
3d69ff21
BA
127 u = 1 - distances2/(sd_dist*h_endo^2)
128 u[abs(u)>1] = 0.
129 u
130 }
131 }
132
133 if (simtype != "endo")
134 {
135 h_exo = ifelse(simtype=="mix", h[2], h)
136
f17665c7 137 M = matrix( nrow=1+length(fdays), ncol=1+length(dat[[today]]$exo) )
dea7ff86 138 M[1,] = c( dat[[today]]$level, as.double(dat[[today]]$exo) )
f17665c7
BA
139 for (i in seq_along(fdays))
140 M[i+1,] = c( dat[[ fdays[i] ]]$level, as.double(dat[[ fdays[i] ]]$exo) )
3d69ff21
BA
141
142 sigma = cov(M) #NOTE: robust covariance is way too slow
613a986f 143 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
3d69ff21
BA
144
145 # Distances from last observed day to days in the past
146 distances2 = rep(NA, nrow(M)-1)
147 for (i in 2:nrow(M))
148 {
149 delta = M[1,] - M[i,]
150 distances2[i-1] = delta %*% sigma_inv %*% delta
151 }
152
153 sd_dist = sd(distances2)
154 simils_exo =
f17665c7 155 if (kernel=="Gauss")
3d69ff21 156 exp(-distances2/(sd_dist*h_exo^2))
f17665c7 157 else { #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
3d69ff21
BA
171
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]
3d69ff21 175 prediction = prediction / sum(similarities, na.rm=TRUE)
99f83c9a 176
3d69ff21
BA
177 if (final_call)
178 {
179 params$weights <<- similarities
180 params$indices <<- fdays_indices
181 params$window <<-
182 if (simtype=="endo") {
183 h_endo
184 } else if (simtype=="exo") {
185 h_exo
f17665c7 186 } else { #mix
3d69ff21
BA
187 c(h_endo,h_exo)
188 }
189 }
99f83c9a 190
3d69ff21
BA
191 return (prediction)
192 }
193 )
194)