fix plots, fix F_Neighbors on series with NAs
[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 NeighborsForecaster = R6::R6Class("NeighborsForecaster",
8 inherit = Forecaster,
9
10 public = list(
11 predictShape = function(data, today, memory, horizon, ...)
12 {
13 # (re)initialize computed parameters
14 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
15
16 # Do not forecast on days with NAs (TODO: softer condition...)
17 if (any(is.na(data$getCenteredSerie(today))))
18 return (NA)
19
20 # Determine indices of no-NAs days followed by no-NAs tomorrows
21 fdays = getNoNA2(data, max(today-memory,1), today-1)
22
23 # Get optional args
24 simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
25 kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
26 if (hasArg(h_window))
27 {
28 return ( private$.predictShapeAux(data,
29 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
30 }
31
32 # Indices of similar days for cross-validation; TODO: 45 = magic number
33 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
34
35 # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
36 errorOnLastNdays = function(h, kernel, simtype)
37 {
38 error = 0
39 nb_jours = 0
40 for (i in intersect(fdays,sdays))
41 {
42 # mix_strategy is never used here (simtype != "mix"), therefore left blank
43 prediction = private$.predictShapeAux(data,
44 fdays, i, horizon, h, kernel, simtype, FALSE)
45 if (!is.na(prediction[1]))
46 {
47 nb_jours = nb_jours + 1
48 error = error +
49 mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
50 }
51 }
52 return (error / nb_jours)
53 }
54
55 if (simtype != "endo")
56 {
57 h_best_exo = optimize(
58 errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
59 }
60 if (simtype != "exo")
61 {
62 h_best_endo = optimize(
63 errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
64 }
65
66 if (simtype == "endo")
67 {
68 return (private$.predictShapeAux(data,
69 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
70 }
71 if (simtype == "exo")
72 {
73 return (private$.predictShapeAux(data,
74 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
75 }
76 if (simtype == "mix")
77 {
78 h_best_mix = c(h_best_endo,h_best_exo)
79 return(private$.predictShapeAux(data,
80 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
81 }
82 }
83 ),
84 private = list(
85 # Precondition: "today" is full (no NAs)
86 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
87 {
88 fdays = fdays[ fdays < today ]
89 # TODO: 3 = magic number
90 if (length(fdays) < 3)
91 return (NA)
92
93 if (simtype != "exo")
94 {
95 h_endo = ifelse(simtype=="mix", h[1], h)
96
97 # Distances from last observed day to days in the past
98 distances2 = rep(NA, length(fdays))
99 for (i in seq_along(fdays))
100 {
101 delta = data$getCenteredSerie(today) - data$getCenteredSerie(fdays[i])
102 # Require at least half of non-NA common values to compute the distance
103 if (sum(is.na(delta)) <= 0) #length(delta)/2)
104 distances2[i] = mean(delta^2) #, na.rm=TRUE)
105 }
106
107 sd_dist = sd(distances2)
108 if (sd_dist < .Machine$double.eps)
109 sd_dist = 1 #mostly for tests... FIXME:
110 simils_endo =
111 if (kernel=="Gauss")
112 exp(-distances2/(sd_dist*h_endo^2))
113 else { #Epanechnikov
114 u = 1 - distances2/(sd_dist*h_endo^2)
115 u[abs(u)>1] = 0.
116 u
117 }
118 }
119
120 if (simtype != "endo")
121 {
122 h_exo = ifelse(simtype=="mix", h[2], h)
123
124 M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
125 M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
126 for (i in seq_along(fdays))
127 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
128
129 sigma = cov(M) #NOTE: robust covariance is way too slow
130 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
131
132 # Distances from last observed day to days in the past
133 distances2 = rep(NA, nrow(M)-1)
134 for (i in 2:nrow(M))
135 {
136 delta = M[1,] - M[i,]
137 distances2[i-1] = delta %*% sigma_inv %*% delta
138 }
139
140 sd_dist = sd(distances2)
141 simils_exo =
142 if (kernel=="Gauss")
143 exp(-distances2/(sd_dist*h_exo^2))
144 else { #Epanechnikov
145 u = 1 - distances2/(sd_dist*h_exo^2)
146 u[abs(u)>1] = 0.
147 u
148 }
149 }
150
151 similarities =
152 if (simtype == "exo")
153 simils_exo
154 else if (simtype == "endo")
155 simils_endo
156 else #mix
157 simils_endo * simils_exo
158
159 prediction = rep(0, horizon)
160 for (i in seq_along(fdays))
161 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
162 prediction = prediction / sum(similarities, na.rm=TRUE)
163
164 if (final_call)
165 {
166 private$.params$weights <- similarities
167 private$.params$indices <- fdays
168 private$.params$window <-
169 if (simtype=="endo") {
170 h_endo
171 } else if (simtype=="exo") {
172 h_exo
173 } else { #mix
174 c(h_endo,h_exo)
175 }
176 }
177
178 return (prediction)
179 }
180 )
181 )