all by-col except M in F_Neighbors.R
[talweg.git] / pkg / R / F_Neighbors.R
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 #'
8 NeighborsForecaster = 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 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
37 errorOnLastNdays = function(h, kernel, simtype)
38 {
39 error = 0
40 nb_jours = 0
41 for (i in intersect(fdays,sdays))
42 {
43 # mix_strategy is never used here (simtype != "mix"), therefore left blank
44 prediction = private$.predictShapeAux(data,
45 fdays, i, horizon, h, kernel, simtype, FALSE)
46 if (!is.na(prediction[1]))
47 {
48 nb_jours = nb_jours + 1
49 error = error +
50 mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
51 }
52 }
53 return (error / nb_jours)
54 }
55
56 if (simtype != "endo")
57 {
58 h_best_exo = optimize(
59 errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
60 }
61 if (simtype != "exo")
62 {
63 h_best_endo = optimize(
64 errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
65 }
66
67 if (simtype == "endo")
68 {
69 return (private$.predictShapeAux(data,
70 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
71 }
72 if (simtype == "exo")
73 {
74 return (private$.predictShapeAux(data,
75 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
76 }
77 if (simtype == "mix")
78 {
79 h_best_mix = c(h_best_endo,h_best_exo)
80 return(private$.predictShapeAux(data,
81 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
82 }
83 }
84 ),
85 private = list(
86 # Precondition: "today" is full (no NAs)
87 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
88 {
89 fdays = fdays[ fdays < today ]
90 # TODO: 3 = magic number
91 if (length(fdays) < 3)
92 return (NA)
93
94 if (simtype != "exo")
95 {
96 h_endo = ifelse(simtype=="mix", h[1], h)
97
98 # Distances from last observed day to days in the past
99 distances2 = rep(NA, length(fdays))
100 for (i in seq_along(fdays))
101 {
102 delta = data$getCenteredSerie(today) - data$getCenteredSerie(fdays[i])
103 # Require at least half of non-NA common values to compute the distance
104 if ( !any( is.na(delta) ) )
105 distances2[i] = mean(delta^2)
106 }
107
108 sd_dist = sd(distances2)
109 if (sd_dist < .Machine$double.eps)
110 {
111 # warning("All computed distances are very close: stdev too small")
112 sd_dist = 1 #mostly for tests... FIXME:
113 }
114 simils_endo =
115 if (kernel=="Gauss")
116 exp(-distances2/(sd_dist*h_endo^2))
117 else
118 {
119 # Epanechnikov
120 u = 1 - distances2/(sd_dist*h_endo^2)
121 u[abs(u)>1] = 0.
122 u
123 }
124 }
125
126 if (simtype != "endo")
127 {
128 h_exo = ifelse(simtype=="mix", h[2], h)
129
130 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
131 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
132 for (i in seq_along(fdays))
133 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
134
135 sigma = cov(M) #NOTE: robust covariance is way too slow
136 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
137
138 # Distances from last observed day to days in the past
139 distances2 = rep(NA, nrow(M)-1)
140 for (i in 2:nrow(M))
141 {
142 delta = M[1,] - M[i,]
143 distances2[i-1] = delta %*% sigma_inv %*% delta
144 }
145
146 sd_dist = sd(distances2)
147 if (sd_dist < .Machine$double.eps)
148 {
149 # warning("All computed distances are very close: stdev too small")
150 sd_dist = 1 #mostly for tests... FIXME:
151 }
152 simils_exo =
153 if (kernel=="Gauss")
154 exp(-distances2/(sd_dist*h_exo^2))
155 else
156 {
157 # 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))
174 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
175 prediction = prediction / sum(similarities, na.rm=TRUE)
176
177 if (final_call)
178 {
179 private$.params$weights <- similarities
180 private$.params$indices <- fdays
181 private$.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 return (prediction)
191 }
192 )
193 )