R/backwardAlg.R

#' backwardAlg
#'
#' \code{backwardAlg} performs the backward algorithm on a single
#' trajecture of observed chain x.
#' \bold{b} (in log scale), where \bold{b[k,t] = P( x[t+1,n]=k | Z[t]=k )}
#'
#' @export
#' @param x     a vector of observed states
#' @param RNA   a 0-1 vector. 1 if next 3-base is stop codon
#' @param trans a vector c(rho_u, rho, delta)
#' @param alpha shape parameter in gamma distribution
#' @param beta  rate parameter in gamma distribution
#' @param E     a scalar. Normalizing constant for the observed chain x.
#' @return      A matrix, \bold{b} (in log scale).
#'
#' @examples
#' df <- uORF[[1]]
#' x=df$x; RNA=df$RNA; trans=df$trans; a=df$v; b=df$v/df$m; E=df$E
#'
#' lb <- backwardAlg(x, RNA, trans, a, b, E)

backwardAlg <- function(x, RNA, trans, alpha, beta, E){
  n <- length(x)
  M <- 21
  lb <- matrix(0, n, M)

  for (t in (n-1):1){
    lf <- lnb(x[t+1], alpha, beta, E)
    lA <- log(transprob(trans, RNA[t], RNA[t]))
    for (k in 1:M){
      ls <- lf  + lA[k,] + lb[t+1,]
      lb[t,k] <- logSumExp(ls)
    }
  }
  colnames(lb) <- seq(1,21)
  return(lb)
}
shimlab/riboHMM2 documentation built on May 19, 2019, 6:23 p.m.