R/fit.R

# Integrate stanfit and stanoptim objects ---------------------------------
# This file contains all the implementation of those methods that should be
# available to both stanfit and stanoptim objects. Our goal is to unify
# these two objects as much as possible for the final user.

# extract_quantity --------------------------------------------------------

#' Extract estimated quantities from fit objects.
#'
#' This function extracts estimated quantities from fit objects. It works transparently with both Markov-chain Monte Carlo samples returned by \code{\link{draw_samples}} and maximum a posteriori estimates returned by \code{\link{optimizing}}. Most of the user-friendly extractors (e.g. \code{\link{extract_alpha}}) are built upon this function. As such, it was not designed to be used directly by users, except perhaps for the most advanced ones.
#'
#' Note that \emph{rstan} does not provide a unified way to extract quantities from full bayesian and optimization fits, and the structure of the returned objects are not homogeneous. \emph{extract_quantity} solves these two inconvenients. Additionally, it allows for regex expressions in the name of the quantities to be extracted.
#'
#' @param fit An object returned by \code{\link{fit}}, \code{\link{draw_samples}}, or \code{\link{optimizing}}.
#' @param pars A vector of characters with the name of the quantities to be extracted. The characters strings may include regular expressions. Further, wildcards are automatically translated into regex: \emph{?} matches a single character, while \emph{*} matches any character string including an empty one. For example, \emph{?pred} will match both ypred and zpred, and \emph{z*} will match zstar and zpred.
#' @param reduce A function applied to the samples generated by one chain for each parameters (i.e. "within chain"). Useful if only one or more summary measures of the generated samples is needed (e.g. the median of the generated sample). The function may return one of more elements. In the former case, the dimension is dropped in the returned object (read the \emph{Value} section below). Note that the user needs to supply a function as an argument, and not a character string with the name of the function. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one scalar per quantity.
#' @param combine A function applied to all the extracted quantities as an ensemble. In other words, instead of returning a named list where each element is one quantity, it returns the value returned by the function applied to the whole list (\code{\link{do.call}}). Useful when all the elements of the list have the same dimension, possibly because it is used in conjunction with the \emph{chain} and \emph{reduce} arguments.
#' @param chain Either "all" or any integer number between 1 and the number of chains M. In the latter case, the chain dimension in the returned object is dropped.
#' @param ... Arguments to be passed to rstan's \code{\link[rstan]{extract}} if the object \emph{fit} was returned by \code{\link{fit}} or \code{\link{draw_samples}}.
#' @return A list of named elements with type and dimension depending on the characteristics of the quantity. If the argument \emph{combine} is set, the returned value equals to the return value of the function given (e.g. a matrix if \code{\link{cbind}}) is used).
#'
#' @examples
#' \dontrun{
#'   extract_quantity(myFit, c("z*"), reduce = mean, chain = 1, combine = cbind))
#' }
extract_quantity <- function(fit, pars, reduce = NULL,
                             combine = NULL, chain = "all", ...) {
  UseMethod("extract_quantity", fit)
}

#' @keywords internal
#' @inherit extract_quantity
extract_quantity.Optimization <- function(fit, pars, reduce = NULL,
                                          combine = NULL, chain = "all", ...) {
  reduce <- NULL # Can't reduce in-chain cause there are not iterations
  ind <- do.call(c, lapply(unique(pars), function(par) {
    grep(
      pattern = glob2rx(sprintf("%s*", par)),
      x       = names(fit$par)
    )})
  )

  xs  <- fit$par[ind]

  l   <- sapply(xs, function(x) {
    drop(if (is.null(reduce)) { x } else { reduce(x) })
  }, simplify = FALSE, USE.NAMES = TRUE)

  if (is.null(combine)) { l } else { drop(do.call(combine, l)) }
}

#' @keywords internal
#' @inherit extract_quantity
extract_quantity.stanfit <- function(fit, pars, reduce = NULL,
                                     combine = NULL, chain = "all", ...) {
  ext <- function(p) {
    # extract and set dimensions: x[iteration, chain, parDims ...]
    x           <- rstan::extract(fit, pars = p, permuted = FALSE, ...)
    parDims     <- if (is.empty(fit@par_dims[[p]])) { 1 } else { fit@par_dims[[p]] }
    dim(x)      <- c(dim(x)[1:2], parDims)

    # reduce but keep dimensions
    if (!is.null(reduce)) {
      oDim   <- dim(x)
      x      <- apply(x, seq.int(2, length(oDim)), reduce)
      dim(x) <- replace(oDim, 1, length(x) / prod(oDim[-1]))
    }

    # subset/merge but keep dimensions
    if (chain == "all")
      invisible({})

    if (chain %in% seq_len(extract_n_chains(fit))) {
      oDim   <- dim(x)
      x      <- x[slice.index(x, 2) == chain]
      dim(x) <- replace(oDim, 2, 1)
    }

    if (chain == "merge")
      warning("extract_quantity.stanfit: Merging chains not yet implemented.")

    return(drop(x))
  }

  pars <- unlist(
    lapply(unique(pars), function(p) {
      grep(pattern = glob2rx(p), extract_parameter_names(fit), value = TRUE)
    })
  )

  l <- sapply(pars, ext, simplify = FALSE, USE.NAMES = TRUE)

  if (is.null(combine))
    return(l)

  drop(do.call(combine, l))
}

# extract_parameter_names -------------------------------------------------

#' Extract the names of all the model parameters in the fit object.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return A character vector with the selected model parameter names.
#' @seealso See \code{\link{select_parameters}} for extracting the names of part of the model.
#' @keywords internal
extract_parameter_names <- function(fit) {
  UseMethod("extract_parameter_names", fit)
}

#' @keywords internal
#' @inherit extract_parameter_names
extract_parameter_names.Optimization <- function(fit) {
  names(fit$par)
}

#' @keywords internal
#' @inherit extract_parameter_names
extract_parameter_names.stanfit <- function(fit) {
  fit@model_pars
}

# extract_date ------------------------------------------------------------
#' Extract the date when the model was run.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return An integer with the date used to fit the model.
extract_date <- function(fit) {
  UseMethod("extract_date", fit)
}

#' @keywords internal
#' @inherit extract_date
extract_date.Optimization <- function(fit) {
  attr(fit, "date")
}

#' @keywords internal
#' @inherit extract_date
extract_date.stanfit <- function(fit) {
  strptime(fit@date, "%a %b %d %H:%M:%S %Y")
}

# extract_time ------------------------------------------------------------
#' Extract the time elapsed when fitting the model.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return For objects fit via \code{\link{draw_samples}}, a named numeric matrix with two columns (warm-up and sample time) and one row per chain. For objects fit via \code{\link{optimizing}}, the system time elapsed.
extract_time <- function(fit) {
  UseMethod("extract_time", fit)
}

#' @keywords internal
#' @inherit extract_time
extract_time.Optimization <- function(fit) {
  attr(fit, "systemTime")
}

#' @keywords internal
#' @inherit extract_time
extract_time.stanfit <- function(fit) {
  rstan::get_elapsed_time(fit)
}

# extract_seed ------------------------------------------------------------
#' Extract the seed used to fit the model.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return An integer with the seed used to fit the model.
extract_seed     <- function(fit) {
  UseMethod("extract_seed", fit)
}

#' @keywords internal
#' @inherit extract_seed
extract_seed.Optimization <- function(fit) {
  attr(fit, "seed")
}

#' @keywords internal
#' @inherit extract_seed
extract_seed.stanfit <- function(fit) {
  rstan::get_seed(fit)
}

# extract_stanmodel -------------------------------------------------------
#' Extract the stanmodel object of the fitted object.
#'
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @return An integer with the stanmodel used to fit the model.
extract_stanmodel     <- function(fit) {
  UseMethod("extract_stanmodel", fit)
}

#' @keywords internal
#' @inherit extract_stanmodel
extract_stanmodel.Optimization <- function(fit) {
  attr(fit, "stanmodel")
}

#' @keywords internal
#' @inherit extract_stanmodel
extract_stanmodel.stanfit <- function(fit) {
  rstan::get_stanmodel(fit)
}

#' @keywords internal
#' @inherit extract_stanmodel
extract_stanmodel.stanmodel <- function(fit) {
  fit
}

# classify_quantity -------------------------------------------------------
#' Classify observations based on latent state probabilities.
#'
#' Assign the hidden states at each time step \emph{t} to the hidden state \emph{k} with largest quantity of interest.
#'
#' @name classify_quantity
#' @param fit An object returned by either \code{\link{draw_samples}} or \code{\link{optimizing}}.
#' @param reduce An optional function applied to the samples corresponding to one time step \emph{t}, one hidden state \emph{k}, and one chain \emph{m}. The observation at time step \emph{t} is then assigned to the hidden state with largest value. Note that the user needs to supply a function as an argument, and not a character string with the name of the function. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one scalar per quantity. It defaults to the \code{\link{mean}} function.
#' @param chain Either "all" or any integer number between 1 and the number of chains M. In the latter case, only the samples generated by the selected chain are considered. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one result. It defaults to "all".
#' @param quantity A character string with the name of the parameter to be classified (most likely a probability such as "alpha" or "gamma"). Note that no every estimated parameter has the structure needed for classification.
#' @return A numeric vector with size equal to the time series length \emph{T} with values from 1 to the number of hidden states \emph{K}.
#' @keywords internal
classify_quantity <- function(fit, reduce, chain, quantity) {
  f <- match.fun(paste0("extract_", quantity))
  q <- f(fit, reduce = reduce, chain = chain)
  dimLength <- length(dim(q))

  if (dimLength < 2) {
    stop("The dimension of the quantity is not enough for me to classify.")
  } else if (length(dim(q)) == 2) {
    return(apply(q, 2, which.max))
  } else {
    return(
      apply(q, 1, function(q) {
        apply(q, 2, which.max)
      })
    )
  }
}

# classify_alpha ----------------------------------------------------------
#' Classify observations based on filtered probabilities.
#'
#' This function assigns the hidden states at each time step \emph{t} to the hidden state \emph{k} with largest estimated filtered probability (\emph{alpha}).
#' @inherit classify_quantity
classify_alpha   <- function(fit, reduce = mean, chain = "all") {
  UseMethod("classify_alpha", fit)
}

#' @keywords internal
#' @inherit classify_alpha
classify_alpha.Optimization <- function(fit, reduce = mean, chain = "all") {
  apply(extract_alpha(fit), 2, which.max)
}

#' @keywords internal
#' @inherit classify_alpha
classify_alpha.stanfit <- function(fit, reduce = mean, chain = "all") {
  classify_quantity(fit, reduce, chain, "alpha")
}

# classify_gamma ----------------------------------------------------------
#' Classify observations based on smoothed probabilities.
#'
#' This function assigns the hidden states at each time step \emph{t} to the hidden state \emph{k} with largest estimated smoothed probability (\emph{gamma}).
#' @inherit classify_quantity
classify_gamma   <- function(fit, reduce = mean, chain = "all") {
  UseMethod("classify_gamma", fit)
}

#' @keywords internal
#' @inherit classify_gamma
classify_gamma.Optimization <- function(fit, reduce = mean, chain = "all") {
  apply(extract_gamma(fit), 2, which.max)
}

#' @keywords internal
#' @inherit classify_gamma
classify_gamma.stanfit <- function(fit, reduce = mean, chain = "all") {
  classify_quantity(fit, reduce, chain, "gamma")
}

# classify_zstar ----------------------------------------------------------
#' Assign the hidden states to the most likely path (\emph{zstar}).
#'
#' This is the result of Viterbi algorithm, which considers the joint distribution of the states.
#' @inherit classify_quantity
#' @param reduce An optional function applied to the samples corresponding to one time step \emph{t}, one hidden state \emph{k}, and one chain \emph{m}. The observation at time step \emph{t} is then assigned to the hidden state with largest value. Note that the user needs to supply a function as an argument, and not a character string with the name of the function. This argument is not used for maximum a posteriori estimates returned by \code{\link{optimizing}} since there is only one scalar per quantity. It defaults to the \code{\link{posterior_mode}} function.
classify_zstar   <- function(fit, reduce = posterior_mode, chain = "all") {
  UseMethod("classify_zstar", fit)
}

#' @keywords internal
#' @inherit classify_zstar
classify_zstar.Optimization <- function(fit, reduce = posterior_mode, chain = "all") {
  extract_zstar(fit)
}

#' @keywords internal
#' @inherit classify_zstar
classify_zstar.stanfit <- function(fit, reduce = posterior_mode, chain = "all") {
  extract_zstar(fit, reduce = reduce, chain = chain)
}
luisdamiano/BayesHMM documentation built on May 20, 2019, 2:59 p.m.