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