TODO: unit tests for simil days
[talweg.git] / pkg / R / F_Neighbors.R
index 7a3fbe5..ffb068f 100644 (file)
-#' @include Forecaster.R
-#'
 #' Neighbors Forecaster
 #'
-#' Predict tomorrow as a weighted combination of "futures of the past" days.
-#' Inherits \code{\link{Forecaster}}
+#' Predict next serie as a weighted combination of "futures of the past" days,
+#' where days in the past are chosen and weighted according to some similarity measures.
+#'
+#' The main method is \code{predictShape()}, taking arguments data, today, memory,
+#' horizon respectively for the dataset (object output of \code{getData()}), the current
+#' index, the data depth (in days) and the number of time steps to forecast.
+#' In addition, optional arguments can be passed:
+#' \itemize{
+#'   \item local : TRUE (default) to constrain neighbors to be "same days within same
+#'     season"
+#'   \item simtype : 'endo' for a similarity based on the series only,<cr>
+#'             'exo' for a similaruty based on exogenous variables only,<cr>
+#'             'mix' for the product of 'endo' and 'exo',<cr>
+#'             'none' (default) to apply a simple average: no computed weights
+#'   \item window : A window for similarities computations; override cross-validation
+#'     window estimation.
+#' }
+#' The method is summarized as follows:
+#' \enumerate{
+#'   \item Determine N (=20) recent days without missing values, and followed by a
+#'     tomorrow also without missing values.
+#'   \item Optimize the window parameters (if relevant) on the N chosen days.
+#'   \item Considering the optimized window, compute the neighbors (with locality
+#'     constraint or not), compute their similarities -- using a gaussian kernel if
+#'     simtype != "none" -- and average accordingly the "tomorrows of neigbors" to
+#'     obtain the final prediction.
+#' }
+#'
+#' @docType class
+#' @format R6 class, inherits Forecaster
+#' @aliases F_Neighbors
+#'
 NeighborsForecaster = R6::R6Class("NeighborsForecaster",
        inherit = Forecaster,
 
        public = list(
-               predictShape = function(today, memory, horizon, ...)
+               predictShape = function(data, today, memory, horizon, ...)
                {
                        # (re)initialize computed parameters
                        private$.params <- list("weights"=NA, "indices"=NA, "window"=NA)
 
+                       # Do not forecast on days with NAs (TODO: softer condition...)
+                       if (any(is.na(data$getCenteredSerie(today))))
+                               return (NA)
+
                        # Determine indices of no-NAs days followed by no-NAs tomorrows
-                       fdays = private$.data$getCoupleDays(max(today-memory,1), today-1)
+                       fdays = .getNoNA2(data, max(today-memory,1), today-1)
 
                        # Get optional args
-                       simtype = ifelse(hasArg("simtype"), list(...)$simtype, "mix") #or "endo", or "exo"
-                       kernel = ifelse(hasArg("kernel"), list(...)$kernel, "Gauss") #or "Epan"
-                       if (hasArg(h_window))
+                       local = ifelse(hasArg("local"), list(...)$local, TRUE) #same level + season?
+                       simtype = ifelse(hasArg("simtype"), list(...)$simtype, "none") #or "endo", or "exo"
+                       if (hasArg("window"))
                        {
-                               return ( private$.predictShapeAux(
-                                       fdays, today, horizon, list(...)$h_window, kernel, simtype, TRUE) )
+                               return ( private$.predictShapeAux(data,
+                                       fdays, today, horizon, local, list(...)$window, simtype, TRUE) )
                        }
 
-                       # Indices of similar days for cross-validation; TODO: 45 = magic number
-                       sdays = getSimilarDaysIndices(today, limit=45, same_season=FALSE)
+                       # Indices of similar days for cross-validation; TODO: 20 = magic number
+                       cv_days = getSimilarDaysIndices(today, data, limit=20, same_season=FALSE,
+                               days_in=fdays)
 
-                       # Function to optimize h : h |--> sum of prediction errors on last 45 "similar" days
-                       errorOnLastNdays = function(h, kernel, simtype)
+                       # Optimize h : h |--> sum of prediction errors on last N "similar" days
+                       errorOnLastNdays = function(window, simtype)
                        {
                                error = 0
                                nb_jours = 0
-                               for (i in intersect(fdays,sdays))
+                               for (i in seq_along(cv_days))
                                {
                                        # mix_strategy is never used here (simtype != "mix"), therefore left blank
-                                       prediction = private$.predictShapeAux(fdays, i, horizon, h, kernel, simtype, FALSE)
+                                       prediction = private$.predictShapeAux(data, fdays, cv_days[i], horizon, local,
+                                               window, simtype, FALSE)
                                        if (!is.na(prediction[1]))
                                        {
                                                nb_jours = nb_jours + 1
                                                error = error +
-                                                       mean((private$.data$getCenteredSerie(i+1)[1:horizon] - prediction)^2)
+                                                       mean((data$getSerie(cv_days[i]+1)[1:horizon] - prediction)^2)
                                        }
                                }
                                return (error / nb_jours)
                        }
 
-                       if (simtype != "endo")
+                       # TODO: 7 == magic number
+                       if (simtype=="endo" || simtype=="mix")
                        {
-                               h_best_exo = optimize(
-                                       errorOnLastNdays, c(0,10), kernel=kernel, simtype="exo")$minimum
+                               best_window_endo = optimize(
+                                       errorOnLastNdays, c(0,7), simtype="endo")$minimum
                        }
-                       if (simtype != "exo")
+                       if (simtype=="exo" || simtype=="mix")
                        {
-                               h_best_endo = optimize(
-                                       errorOnLastNdays, c(0,10), kernel=kernel, simtype="endo")$minimum
+                               best_window_exo = optimize(
+                                       errorOnLastNdays, c(0,7), simtype="exo")$minimum
                        }
 
-                       if (simtype == "endo")
-                       {
-                               return (private$.predictShapeAux(
-                                       fdays, today, horizon, h_best_endo, kernel, "endo", TRUE))
-                       }
-                       if (simtype == "exo")
-                       {
-                               return (private$.predictShapeAux(
-                                       fdays, today, horizon, h_best_exo, kernel, "exo", TRUE))
-                       }
-                       if (simtype == "mix")
-                       {
-                               h_best_mix = c(h_best_endo,h_best_exo)
-                               return(private$.predictShapeAux(
-                                       fdays, today, horizon, h_best_mix, kernel, "mix", TRUE))
-                       }
+                       best_window =
+                               if (simtype == "endo")
+                                       best_window_endo
+                               else if (simtype == "exo")
+                                       best_window_exo
+                               else if (simtype == "mix")
+                                       c(best_window_endo,best_window_exo)
+                               else #none: value doesn't matter
+                                       1
+
+                       return(private$.predictShapeAux(data, fdays, today, horizon, local,
+                               best_window, simtype, TRUE))
                }
        ),
        private = list(
                # Precondition: "today" is full (no NAs)
-               .predictShapeAux = function(fdays, today, horizon, h, kernel, simtype, final_call)
+               .predictShapeAux = function(data, fdays, today, horizon, local, window, simtype,
+                       final_call)
                {
-                       fdays = fdays[ fdays < today ]
-                       # TODO: 3 = magic number
-                       if (length(fdays) < 3)
+                       fdays_cut = fdays[ fdays < today ]
+                       if (length(fdays_cut) <= 1)
                                return (NA)
 
-                       data = private$.data #shorthand
+                       if (local)
+                       {
+                               # TODO: 60 == magic number
+                               fdays = getSimilarDaysIndices(today, data, limit=60, same_season=TRUE,
+                                       days_in=fdays_cut)
+                               if (length(fdays) <= 1)
+                                       return (NA)
+                               # TODO: 10, 12 == magic numbers
+                               fdays = .getConstrainedNeighbs(today,data,fdays,min_neighbs=10,max_neighbs=12)
+                               if (length(fdays) == 1)
+                               {
+                                       if (final_call)
+                                       {
+                                               private$.params$weights <- 1
+                                               private$.params$indices <- fdays
+                                               private$.params$window <- 1
+                                       }
+                                       return ( data$getSerie(fdays[1])[1:horizon] )
+                               }
+                       }
+                       else
+                               fdays = fdays_cut #no conditioning
 
-                       if (simtype != "exo")
+                       if (simtype == "endo" || simtype == "mix")
                        {
-                               h_endo = ifelse(simtype=="mix", h[1], h)
+                               # Compute endogen similarities using given window
+                               window_endo = ifelse(simtype=="mix", window[1], window)
 
                                # Distances from last observed day to days in the past
-                               distances2 = rep(NA, length(fdays))
-                               for (i in seq_along(fdays))
-                               {
-                                       delta = data$getCenteredSerie(today) - data$getCenteredSerie(fdays[i])
-                                       # Require at least half of non-NA common values to compute the distance
-                                       if (sum(is.na(delta)) <= 0) #length(delta)/2)
-                                               distances2[i] = mean(delta^2) #, na.rm=TRUE)
-                               }
+                               serieToday = data$getSerie(today)
+                               distances2 = sapply(fdays, function(i) {
+                                       delta = serieToday - data$getSerie(i)
+                                       mean(delta^2)
+                               })
 
-                               sd_dist = sd(distances2)
-                               if (sd_dist < .Machine$double.eps)
-                                       sd_dist = 1 #mostly for tests... FIXME:
-                               simils_endo =
-                                       if (kernel=="Gauss")
-                                               exp(-distances2/(sd_dist*h_endo^2))
-                                       else { #Epanechnikov
-                                               u = 1 - distances2/(sd_dist*h_endo^2)
-                                               u[abs(u)>1] = 0.
-                                               u
-                                       }
+                               simils_endo <- .computeSimils(distances2, window_endo)
                        }
 
-                       if (simtype != "endo")
+                       if (simtype == "exo" || simtype == "mix")
                        {
-                               h_exo = ifelse(simtype=="mix", h[2], h)
+                               # Compute exogen similarities using given window
+                               window_exo = ifelse(simtype=="mix", window[2], window)
 
                                M = matrix( nrow=1+length(fdays), ncol=1+length(data$getExo(today)) )
                                M[1,] = c( data$getLevel(today), as.double(data$getExo(today)) )
@@ -124,25 +165,20 @@ NeighborsForecaster = R6::R6Class("NeighborsForecaster",
                                        M[i+1,] = c( data$getLevel(fdays[i]), as.double(data$getExo(fdays[i])) )
 
                                sigma = cov(M) #NOTE: robust covariance is way too slow
-                               sigma_inv = solve(sigma) #TODO: use pseudo-inverse if needed?
+                               # TODO: 10 == magic number; more robust way == det, or always ginv()
+                               sigma_inv =
+                                       if (length(fdays) > 10)
+                                               solve(sigma)
+                                       else
+                                               MASS::ginv(sigma)
 
                                # Distances from last observed day to days in the past
-                               distances2 = rep(NA, nrow(M)-1)
-                               for (i in 2:nrow(M))
-                               {
-                                       delta = M[1,] - M[i,]
-                                       distances2[i-1] = delta %*% sigma_inv %*% delta
-                               }
+                               distances2 = sapply(seq_along(fdays), function(i) {
+                                       delta = M[1,] - M[i+1,]
+                                       delta %*% sigma_inv %*% delta
+                               })
 
-                               sd_dist = sd(distances2)
-                               simils_exo =
-                                       if (kernel=="Gauss")
-                                               exp(-distances2/(sd_dist*h_exo^2))
-                                       else { #Epanechnikov
-                                               u = 1 - distances2/(sd_dist*h_exo^2)
-                                               u[abs(u)>1] = 0.
-                                               u
-                                       }
+                               simils_exo <- .computeSimils(distances2, window_exo)
                        }
 
                        similarities =
@@ -150,29 +186,101 @@ NeighborsForecaster = R6::R6Class("NeighborsForecaster",
                                        simils_exo
                                else if (simtype == "endo")
                                        simils_endo
-                               else #mix
+                               else if (simtype == "mix")
                                        simils_endo * simils_exo
+                               else #none
+                                       rep(1, length(fdays))
+                       similarities = similarities / sum(similarities)
 
                        prediction = rep(0, horizon)
                        for (i in seq_along(fdays))
                                prediction = prediction + similarities[i] * data$getSerie(fdays[i]+1)[1:horizon]
-                       prediction = prediction / sum(similarities, na.rm=TRUE)
 
                        if (final_call)
                        {
                                private$.params$weights <- similarities
                                private$.params$indices <- fdays
                                private$.params$window <-
-                                       if (simtype=="endo") {
-                                               h_endo
-                                       } else if (simtype=="exo") {
-                                               h_exo
-                                       } else { #mix
-                                               c(h_endo,h_exo)
-                                       }
+                                       if (simtype=="endo")
+                                               window_endo
+                                       else if (simtype=="exo")
+                                               window_exo
+                                       else if (simtype=="mix")
+                                               c(window_endo,window_exo)
+                                       else #none
+                                               1
                        }
 
                        return (prediction)
                }
        )
 )
+
+#' getNoNA2
+#'
+#' Get indices in data of no-NA series followed by no-NA, within [first,last] range.
+#'
+#' @inheritParams dateIndexToInteger
+#' @param first First index (included)
+#' @param last Last index (included)
+#'
+.getNoNA2 = function(data, first, last)
+{
+       (first:last)[ sapply(first:last, function(i)
+               !any( is.na(data$getCenteredSerie(i)) | is.na(data$getCenteredSerie(i+1)) )
+       ) ]
+}
+
+#' getConstrainedNeighbs
+#'
+#' Get indices of neighbors of similar pollution level (among same season + day type).
+#'
+#' @param today Index of current day
+#' @param data Object of class Data
+#' @param fdays Current set of "first days" (no-NA pairs)
+#' @param min_neighbs Minimum number of points in a neighborhood
+#' @param max_neighbs Maximum number of points in a neighborhood
+#'
+.getConstrainedNeighbs = function(today, data, fdays, min_neighbs=10, max_neighbs=12)
+{
+       levelToday = data$getLevel(today)
+       distances = sapply(fdays, function(i) abs(data$getLevel(i)-levelToday))
+       #TODO: 2, +3 : magic numbers
+       dist_thresh = 2
+       min_neighbs = min(min_neighbs,length(fdays))
+       repeat
+       {
+               same_pollution = (distances <= dist_thresh)
+               nb_neighbs = sum(same_pollution)
+               if (nb_neighbs >= min_neighbs) #will eventually happen
+                       break
+               dist_thresh = dist_thresh + 3
+       }
+       fdays = fdays[same_pollution]
+       max_neighbs = 12
+       if (nb_neighbs > max_neighbs)
+       {
+               # Keep only max_neighbs closest neighbors
+               fdays = fdays[
+                       sort(distances[same_pollution],index.return=TRUE)$ix[1:max_neighbs] ]
+       }
+       fdsays
+}
+
+#' compute similarities
+#'
+#' Apply the gaussian kernel on computed squared distances.
+#'
+#' @param distances2 Squared distances
+#' @param window Window parameter for the kernel
+#'
+.computeSimils <- function(distances2, window)
+{
+       sd_dist = sd(distances2)
+       if (sd_dist < .25 * sqrt(.Machine$double.eps))
+       {
+#              warning("All computed distances are very close: stdev too small")
+               sd_dist = 1 #mostly for tests... FIXME:
+       }
+       exp(-distances2/(sd_dist*window^2))
+}