43a6a13a1d82d7d15d7ec9c6519aeb1084f9309c
[talweg.git] / pkg / R / F_Neighbors.R
1 #' @include Forecaster.R
2 #'
3 #' @title Neighbors Forecaster
4 #'
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",
10
11 methods = list(
12 initialize = function(...)
13 {
14 callSuper(...)
15 },
16 predictShape = function(today, memory, horizon, ...)
17 {
18 # (re)initialize computed parameters
19 params <<- list("weights"=NA, "indices"=NA, "window"=NA)
20
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))
26
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))
30 {
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 }
53
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)))
58 }) ]
59
60 # Indices of similar days for cross-validation; TODO: 45 = magic number
61 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
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
68 for (i in intersect(fdays,sdays))
69 {
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]))
73 {
74 nb_jours = nb_jours + 1
75 error = error + mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
76 }
77 }
78 return (error / nb_jours)
79 }
80
81 if (simtype != "endo")
82 h_best_exo = optimize(errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
83 if (simtype != "exo")
84 h_best_endo = optimize(errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
85
86 if (simtype == "endo")
87 return (.predictShapeAux(fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
88 if (simtype == "exo")
89 return (.predictShapeAux(fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
90 if (simtype == "mix")
91 {
92 h_best_mix = c(h_best_endo,h_best_exo)
93 return (.predictShapeAux(fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
94 }
95 },
96 # Precondition: "today" is full (no NAs)
97 .predictShapeAux = function(fdays, today, horizon, h, kernel, simtype, final_call)
98 {
99 dat = data$data #HACK: faster this way...
100
101 fdays = fdays[ fdays < today ]
102 # TODO: 3 = magic number
103 if (length(fdays) < 3)
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
111 distances2 = rep(NA, length(fdays))
112 for (i in seq_along(fdays))
113 {
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)
118 }
119
120 sd_dist = sd(distances2)
121 if (sd_dist < .Machine$double.eps)
122 sd_dist = 1 #mostly for tests... FIXME:
123 simils_endo =
124 if (kernel=="Gauss")
125 exp(-distances2/(sd_dist*h_endo^2))
126 else { #Epanechnikov
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
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) )
141
142 sigma = cov(M) #NOTE: robust covariance is way too slow
143 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
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 =
155 if (kernel=="Gauss")
156 exp(-distances2/(sd_dist*h_exo^2))
157 else { #Epanechnikov
158 u = 1 - distances2/(sd_dist*h_exo^2)
159 u[abs(u)>1] = 0.
160 u
161 }
162 }
163
164 similarities =
165 if (simtype == "exo")
166 simils_exo
167 else if (simtype == "endo")
168 simils_endo
169 else #mix
170 simils_endo * simils_exo
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]
175 prediction = prediction / sum(similarities, na.rm=TRUE)
176
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
186 } else { #mix
187 c(h_endo,h_exo)
188 }
189 }
190
191 return (prediction)
192 }
193 )
194 )