Simplify plots: version OK with R6 classes
[talweg.git] / pkg / R / F_Neighbors.R
CommitLineData
e030a6e3 1#' @include Forecaster.R
3d69ff21 2#'
25b75559 3#' Neighbors Forecaster
3d69ff21 4#'
25b75559
BA
5#' Predict tomorrow as a weighted combination of "futures of the past" days.
6#' Inherits \code{\link{Forecaster}}
7NeighborsForecaster = R6::R6Class("NeighborsForecaster",
a66a84b5 8 inherit = Forecaster,
25b75559
BA
9
10 public = list(
98e958ca 11 predictShape = function(data, today, memory, horizon, ...)
3d69ff21
BA
12 {
13 # (re)initialize computed parameters
a66a84b5 14 private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
3d69ff21 15
af3b84f4 16 # Determine indices of no-NAs days followed by no-NAs tomorrows
98e958ca 17 fdays = getNoNA2(data, max(today-memory,1), today-1)
af3b84f4 18
f17665c7
BA
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))
a66a84b5 23 {
98e958ca 24 return ( private$.predictShapeAux(data,
a66a84b5
BA
25 fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
26 }
3d69ff21 27
f17665c7
BA
28 # Indices of similar days for cross-validation; TODO: 45 = magic number
29 sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
3d69ff21
BA
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
f17665c7 36 for (i in intersect(fdays,sdays))
3d69ff21 37 {
f17665c7 38 # mix_strategy is never used here (simtype != "mix"), therefore left blank
98e958ca
BA
39 prediction = private$.predictShapeAux(data,
40 fdays, i, horizon, h, kernel, simtype, FALSE)
f17665c7 41 if (!is.na(prediction[1]))
3d69ff21
BA
42 {
43 nb_jours = nb_jours + 1
af3b84f4 44 error = error +
98e958ca 45 mean((data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
3d69ff21
BA
46 }
47 }
48 return (error / nb_jours)
49 }
50
f17665c7 51 if (simtype != "endo")
af3b84f4
BA
52 {
53 h_best_exo = optimize(
54 errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
55 }
3d69ff21 56 if (simtype != "exo")
af3b84f4
BA
57 {
58 h_best_endo = optimize(
59 errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
60 }
3d69ff21
BA
61
62 if (simtype == "endo")
af3b84f4 63 {
98e958ca 64 return (private$.predictShapeAux(data,
af3b84f4
BA
65 fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
66 }
3d69ff21 67 if (simtype == "exo")
af3b84f4 68 {
98e958ca 69 return (private$.predictShapeAux(data,
af3b84f4
BA
70 fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
71 }
3d69ff21
BA
72 if (simtype == "mix")
73 {
f17665c7 74 h_best_mix = c(h_best_endo,h_best_exo)
98e958ca 75 return(private$.predictShapeAux(data,
af3b84f4 76 fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
3d69ff21 77 }
25b75559
BA
78 }
79 ),
80 private = list(
3d69ff21 81 # Precondition: "today" is full (no NAs)
98e958ca 82 .predictShapeAux = function(data, fdays, today, horizon, h, kernel, simtype, final_call)
3d69ff21 83 {
f17665c7 84 fdays = fdays[ fdays < today ]
3d69ff21 85 # TODO: 3 = magic number
f17665c7 86 if (length(fdays) < 3)
3d69ff21
BA
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
f17665c7
BA
94 distances2 = rep(NA, length(fdays))
95 for (i in seq_along(fdays))
3d69ff21 96 {
25b75559 97 delta = data$getCenteredSerie(today) - data$getCenteredSerie(fdays[i])
3d69ff21
BA
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)
99f83c9a
BA
104 if (sd_dist < .Machine$double.eps)
105 sd_dist = 1 #mostly for tests... FIXME:
3d69ff21 106 simils_endo =
99f83c9a 107 if (kernel=="Gauss")
3d69ff21 108 exp(-distances2/(sd_dist*h_endo^2))
99f83c9a 109 else { #Epanechnikov
3d69ff21
BA
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
25b75559
BA
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)) )
f17665c7 122 for (i in seq_along(fdays))
25b75559 123 M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
3d69ff21
BA
124
125 sigma = cov(M) #NOTE: robust covariance is way too slow
613a986f 126 sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
3d69ff21
BA
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 =
f17665c7 138 if (kernel=="Gauss")
3d69ff21 139 exp(-distances2/(sd_dist*h_exo^2))
f17665c7 140 else { #Epanechnikov
3d69ff21
BA
141 u = 1 - distances2/(sd_dist*h_exo^2)
142 u[abs(u)>1] = 0.
143 u
144 }
145 }
146
3d69ff21 147 similarities =
f17665c7 148 if (simtype == "exo")
3d69ff21 149 simils_exo
f17665c7
BA
150 else if (simtype == "endo")
151 simils_endo
152 else #mix
153 simils_endo * simils_exo
3d69ff21
BA
154
155 prediction = rep(0, horizon)
a66a84b5
BA
156 for (i in seq_along(fdays))
157 prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
3d69ff21 158 prediction = prediction / sum(similarities, na.rm=TRUE)
99f83c9a 159
3d69ff21
BA
160 if (final_call)
161 {
a66a84b5
BA
162 private$.params$weights <- similarities
163 private$.params$indices <- fdays
164 private$.params$window <-
3d69ff21
BA
165 if (simtype=="endo") {
166 h_endo
167 } else if (simtype=="exo") {
168 h_exo
f17665c7 169 } else { #mix
3d69ff21
BA
170 c(h_endo,h_exo)
171 }
172 }
99f83c9a 173
3d69ff21
BA
174 return (prediction)
175 }
176 )
177)