R/RcppExports.R

Defines functions .testthatAbsorbingAreRecurrentClassRcpp .testthatHittingAreOneRcpp .testthatRecurrentHittingRcpp .testthatAreMeanNumVisitsRcpp .testthatAreHittingRcpp .testthatIsPartitionRcpp .approxEqualMatricesRcpp .testthatIsAccesibleRcpp .isProbabilityVector .isStochasticMatrix .isProbability .minNumVisitsRcpp .meanRecurrenceTimeRcpp .meanFirstPassageTimeRcpp .absorptionProbabilitiesRcpp .meanAbsorptionTimeRcpp .isRegularRcpp .isIrreducibleRcpp .absorbingStatesRcpp .steadyStatesRcpp .canonicFormRcpp .hittingProbabilitiesRcpp priorDistribution predictiveDistribution period .gcdRcpp .expectedRewardsBeforeHittingARCpp .expectedRewardsRCpp .firstPassageMultipleRCpp .firstpassageKernelRcpp .summaryKernelRcpp .isAccessibleRcpp .reachabilityMatrixRcpp .transientClassesRcpp .recurrentClassesRcpp .recurrentStatesRcpp .transientStatesRcpp .communicatingClassesRcpp .commClassesKernelRcpp .multinomialCIRcpp .multinomialCIForRowRcpp .noofVisitsDistRCpp markovchainFit inferHyperparam .list2Mc .matr2Mc .mcListFitForList createSequenceMatrix .markovchainSequenceParallelRcpp .markovchainListRcpp .markovchainSequenceRcpp seq2matHigh seq2freqProb .impreciseProbabilityatTRCpp .probabilityatTRCpp .ExpectedTimeRCpp ctmcFit generatorToTransitionMatrix .isGenRcpp

Documented in createSequenceMatrix ctmcFit generatorToTransitionMatrix inferHyperparam markovchainFit period predictiveDistribution priorDistribution seq2freqProb seq2matHigh

# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

.isGenRcpp <- function(gen) {
    .Call(`_markovchain_isGen`, gen)
}

#' @name generatorToTransitionMatrix
#' @title Function to obtain the transition matrix from the generator
#' @description The transition matrix of the embedded DTMC is inferred from the CTMC's generator
#'
#' @usage generatorToTransitionMatrix(gen, byrow = TRUE)
#'
#' @param gen The generator matrix
#' @param byrow Flag to determine if rows (columns) sum to 0
#' @return Returns the transition matrix.
#' 
#' @references
#' Introduction to Stochastic Processes with Applications in the Biosciences (2013), David F.
#' Anderson, University of Wisconsin at Madison
#' 
#' @author Sai Bhargav Yalamanchi
#' @seealso \code{\link{rctmc}},\code{\link{ctmc-class}}
#' @examples
#' energyStates <- c("sigma", "sigma_star")
#' byRow <- TRUE
#' gen <- matrix(data = c(-3, 3, 1, -1), nrow = 2,
#'               byrow = byRow, dimnames = list(energyStates, energyStates))
#' generatorToTransitionMatrix(gen)
#' 
#' @export
generatorToTransitionMatrix <- function(gen, byrow = TRUE) {
    .Call(`_markovchain_generatorToTransitionMatrix`, gen, byrow)
}

#' @name ctmcFit
#' @title Function to fit a CTMC
#' @description This function fits the underlying CTMC give the state
#'   transition data and the transition times using the maximum likelihood
#'   method (MLE)
#' @usage ctmcFit(data, byrow = TRUE, name = "", confidencelevel = 0.95)
#' @param data It is a list of two elements. The first element is a character
#'   vector denoting the states. The second is a numeric vector denoting the
#'   corresponding transition times.
#' @param byrow Determines if the output transition probabilities of the
#'   underlying embedded DTMC are by row.
#' @param name Optional name for the CTMC.
#' @param confidencelevel Confidence level for the confidence interval
#'   construnction.
#' @return It returns a list containing the CTMC object and the confidence intervals.
#' 
#' @details  Note that in data, there must exist an element wise corresponding
#'   between the two elements of the list and that data[[2]][1] is always 0.
#' @references Continuous Time Markov Chains (vignette), Sai Bhargav Yalamanchi, Giorgio Alfredo Spedicato 2015
#' @author Sai Bhargav Yalamanchi
#' @seealso \code{\link{rctmc}}
#' 
#' @examples
#' data <- list(c("a", "b", "c", "a", "b", "a", "c", "b", "c"), c(0, 0.8, 2.1, 2.4, 4, 5, 5.9, 8.2, 9))
#' ctmcFit(data)
#' 
#' @export
#' 
ctmcFit <- function(data, byrow = TRUE, name = "", confidencelevel = 0.95) {
    .Call(`_markovchain_ctmcFit`, data, byrow, name, confidencelevel)
}

.ExpectedTimeRCpp <- function(x, y) {
    .Call(`_markovchain_ExpectedTimeRcpp`, x, y)
}

.probabilityatTRCpp <- function(y) {
    .Call(`_markovchain_probabilityatTRCpp`, y)
}

.impreciseProbabilityatTRCpp <- function(C, i, t, s, error) {
    .Call(`_markovchain_impreciseProbabilityatTRCpp`, C, i, t, s, error)
}

#' @export
seq2freqProb <- function(sequence) {
    .Call(`_markovchain_seq2freqProb`, sequence)
}

#' @export
seq2matHigh <- function(sequence, order) {
    .Call(`_markovchain_seq2matHigh`, sequence, order)
}

.markovchainSequenceRcpp <- function(n, markovchain, t0, include_t0 = FALSE) {
    .Call(`_markovchain_markovchainSequenceRcpp`, n, markovchain, t0, include_t0)
}

.markovchainListRcpp <- function(n, object, include_t0 = FALSE, t0 = character()) {
    .Call(`_markovchain_markovchainListRcpp`, n, object, include_t0, t0)
}

.markovchainSequenceParallelRcpp <- function(listObject, n, include_t0 = FALSE, init_state = character()) {
    .Call(`_markovchain_markovchainSequenceParallelRcpp`, listObject, n, include_t0, init_state)
}

#' @rdname markovchainFit
#' 
#' @export
createSequenceMatrix <- function(stringchar, toRowProbs = FALSE, sanitize = FALSE, possibleStates = character()) {
    .Call(`_markovchain_createSequenceMatrix`, stringchar, toRowProbs, sanitize, possibleStates)
}

.mcListFitForList <- function(data) {
    .Call(`_markovchain_mcListFitForList`, data)
}

.matr2Mc <- function(matrData, laplacian = 0, sanitize = FALSE, possibleStates = character()) {
    .Call(`_markovchain__matr2Mc`, matrData, laplacian, sanitize, possibleStates)
}

.list2Mc <- function(data, laplacian = 0, sanitize = FALSE) {
    .Call(`_markovchain__list2Mc`, data, laplacian, sanitize)
}

#' @name inferHyperparam
#' @title Function to infer the hyperparameters for Bayesian inference from an a priori matrix or a data set
#' @description Since the Bayesian inference approach implemented in the package is based on conjugate priors, 
#'              hyperparameters must be provided to model the prior probability distribution of the chain 
#'              parameters. The hyperparameters are inferred from a given a priori matrix under the assumption 
#'              that the matrix provided corresponds to the mean (expected) values of the chain parameters. A 
#'              scaling factor vector must be provided too. Alternatively, the hyperparameters can be inferred 
#'              from a data set. 
#'              
#' @param transMatr A valid transition matrix, with dimension names.
#' @param scale A vector of scaling factors, each element corresponds to the row names of the provided transition 
#'              matrix transMatr, in the same order. 
#' @param data A data set from which the hyperparameters are inferred.  
#' 
#' @details transMatr and scale need not be provided if data is provided.
#' @return Returns the hyperparameter matrix in a list.
#' 
#' @note The hyperparameter matrix returned is such that the row and column names are sorted alphanumerically, 
#'       and the elements in the matrix are correspondingly permuted. 
#' 
#' @references Yalamanchi SB, Spedicato GA (2015). Bayesian Inference of First Order Markov Chains. R
#'             package version 0.2.5       
#'             
#' @author Sai Bhargav Yalamanchi, Giorgio Spedicato
#' @seealso \code{\link{markovchainFit}}, \code{\link{predictiveDistribution}}
#' 
#' @examples
#' data(rain, package = "markovchain")
#' inferHyperparam(data = rain$rain)
#'  
#' weatherStates <- c("sunny", "cloudy", "rain")
#' weatherMatrix <- matrix(data = c(0.7, 0.2, 0.1, 
#'                                  0.3, 0.4, 0.3, 
#'                                  0.2, 0.4, 0.4), 
#'                         byrow = TRUE, nrow = 3, 
#'                         dimnames = list(weatherStates, weatherStates))
#' inferHyperparam(transMatr = weatherMatrix, scale = c(10, 10, 10))
#'  
#' @export
#'  
inferHyperparam <- function(transMatr = matrix(), scale = numeric(), data = character()) {
    .Call(`_markovchain_inferHyperparam`, transMatr, scale, data)
}

#' @name markovchainFit
#' @title Function to fit a discrete Markov chain
#' @description Given a sequence of states arising from a stationary state, 
#'  it fits the underlying Markov chain distribution using either MLE (also using a 
#'  Laplacian smoother), bootstrap or by MAP (Bayesian) inference.
#'  
#' @param data It can be a character vector or a \deqn{n x n} matrix or a \deqn{n x n} data frame or a list
#' @param method Method used to estimate the Markov chain. Either "mle", "map", "bootstrap" or "laplace"
#' @param byrow it tells whether the output Markov chain should show the transition probabilities by row.
#' @param nboot Number of bootstrap replicates in case "bootstrap" is used.
#' @param laplacian Laplacian smoothing parameter, default zero. It is only used when "laplace" method 
#'                  is chosen.  
#' @param name Optional character for name slot. 
#' @param parallel Use parallel processing when performing Boostrap estimates.
#' @param confidencelevel \deqn{\alpha} level for conficence intervals width. 
#'                        Used only when \code{method} equal to "mle".
#' @param confint a boolean to decide whether to compute Confidence Interval or not.                       
#' @param hyperparam Hyperparameter matrix for the a priori distribution. If none is provided, 
#'                   default value of 1 is assigned to each parameter. This must be of size
#'                   \deqn{k x k} where k is the number of states in the chain and the values
#'                   should typically be non-negative integers.                        
#' @param stringchar It can be a \deqn{n x n} matrix or a character vector or a list
#' @param toRowProbs converts a sequence matrix into a probability matrix
#' @param sanitize put 1 in all rows having rowSum equal to zero
#' @param possibleStates Possible states which are not present in the given sequence
#' 
#' @details Disabling confint would lower the computation time on large datasets. If \code{data} or \code{stringchar} 
#' contain \code{NAs}, the related \code{NA} containing transitions will be ignored.
#' 
#' @return A list containing an estimate, log-likelihood, and, when "bootstrap" method is used, a matrix 
#'         of standards deviations and the bootstrap samples. When the "mle", "bootstrap" or "map" method 
#'         is used, the lower and upper confidence bounds are returned along with the standard error. 
#'         The "map" method also returns the expected value of the parameters with respect to the 
#'         posterior distribution.
#' @references A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
#'             
#'             Inferring Markov Chains: Bayesian Estimation, Model Comparison, Entropy Rate, 
#'             and Out-of-Class Modeling, Christopher C. Strelioff, James P. Crutchfield, 
#'             Alfred Hubler, Santa Fe Institute
#' 
#'             Yalamanchi SB, Spedicato GA (2015). Bayesian Inference of First Order Markov Chains. R
#'             package version 0.2.5          
#'             
#' @author Giorgio Spedicato, Tae Seung Kang, Sai Bhargav Yalamanchi
#' @note This function has been rewritten in Rcpp. Bootstrap algorithm has been defined "heuristically". 
#'       In addition, parallel facility is not complete, involving only a part of the bootstrap process.
#'       When \code{data} is either a \code{data.frame} or a \code{matrix} object, only MLE fit is 
#'       currently available.
#'       
#' @seealso \code{\link{markovchainSequence}}, \code{\link{markovchainListFit}}
#' @examples
#' sequence <- c("a", "b", "a", "a", "a", "a", "b", "a", "b", "a", "b", "a", "a", 
#'               "b", "b", "b", "a")        
#' sequenceMatr <- createSequenceMatrix(sequence, sanitize = FALSE)
#' mcFitMLE <- markovchainFit(data = sequence)
#' mcFitBSP <- markovchainFit(data = sequence, method = "bootstrap", nboot = 5, name = "Bootstrap Mc")
#'
#' na.sequence <- c("a", NA, "a", "b")
#' # There will be only a (a,b) transition        
#' na.sequenceMatr <- createSequenceMatrix(na.sequence, sanitize = FALSE)
#' mcFitMLE <- markovchainFit(data = na.sequence)
#' 
#' # data can be a list of character vectors
#' sequences <- list(x = c("a", "b", "a"), y = c("b", "a", "b", "a", "c"))
#' mcFitMap <- markovchainFit(sequences, method = "map")
#' mcFitMle <- markovchainFit(sequences, method = "mle")
#' @rdname markovchainFit
#' 
#' @export
#' 
markovchainFit <- function(data, method = "mle", byrow = TRUE, nboot = 10L, laplacian = 0, name = "", parallel = FALSE, confidencelevel = 0.95, confint = TRUE, hyperparam = matrix(), sanitize = FALSE, possibleStates = character()) {
    .Call(`_markovchain_markovchainFit`, data, method, byrow, nboot, laplacian, name, parallel, confidencelevel, confint, hyperparam, sanitize, possibleStates)
}

.noofVisitsDistRCpp <- function(matrix, i, N) {
    .Call(`_markovchain_noofVisitsDistRCpp`, matrix, i, N)
}

.multinomialCIForRowRcpp <- function(x, confidencelevel) {
    .Call(`_markovchain_multinomialCIForRow`, x, confidencelevel)
}

.multinomialCIRcpp <- function(transMat, seqMat, confidencelevel) {
    .Call(`_markovchain_multinomCI`, transMat, seqMat, confidencelevel)
}

.commClassesKernelRcpp <- function(P) {
    .Call(`_markovchain_commClassesKernel`, P)
}

.communicatingClassesRcpp <- function(object) {
    .Call(`_markovchain_communicatingClasses`, object)
}

.transientStatesRcpp <- function(object) {
    .Call(`_markovchain_transientStates`, object)
}

.recurrentStatesRcpp <- function(object) {
    .Call(`_markovchain_recurrentStates`, object)
}

.recurrentClassesRcpp <- function(object) {
    .Call(`_markovchain_recurrentClasses`, object)
}

.transientClassesRcpp <- function(object) {
    .Call(`_markovchain_transientClasses`, object)
}

.reachabilityMatrixRcpp <- function(obj) {
    .Call(`_markovchain_reachabilityMatrix`, obj)
}

.isAccessibleRcpp <- function(obj, from, to) {
    .Call(`_markovchain_isAccessible`, obj, from, to)
}

.summaryKernelRcpp <- function(object) {
    .Call(`_markovchain_summaryKernel`, object)
}

.firstpassageKernelRcpp <- function(P, i, n) {
    .Call(`_markovchain_firstpassageKernel`, P, i, n)
}

.firstPassageMultipleRCpp <- function(P, i, setno, n) {
    .Call(`_markovchain_firstPassageMultipleRCpp`, P, i, setno, n)
}

.expectedRewardsRCpp <- function(matrix, n, rewards) {
    .Call(`_markovchain_expectedRewardsRCpp`, matrix, n, rewards)
}

.expectedRewardsBeforeHittingARCpp <- function(matrix, s0, rewards, n) {
    .Call(`_markovchain_expectedRewardsBeforeHittingARCpp`, matrix, s0, rewards, n)
}

.gcdRcpp <- function(a, b) {
    .Call(`_markovchain_gcd`, a, b)
}

#' @rdname structuralAnalysis
#' 
#' @export
period <- function(object) {
    .Call(`_markovchain_period`, object)
}

#' @title predictiveDistribution
#'
#' @description The function computes the probability of observing a new data
#'   set, given a data set
#' @usage predictiveDistribution(stringchar, newData, hyperparam = matrix())
#'
#' @param stringchar This is the data using which the Bayesian inference is
#'   performed.
#' @param newData This is the data whose predictive probability is computed.
#' @param hyperparam This determines the shape of the prior distribution of the
#'   parameters. If none is provided, default value of 1 is assigned to each
#'   parameter. This must be of size kxk where k is the number of states in the
#'   chain and the values should typically be non-negative integers.
#' @return The log of the probability is returned.
#'
#' @details The underlying method is Bayesian inference. The probability is
#'   computed by averaging the likelihood of the new data with respect to the
#'   posterior. Since the method assumes conjugate priors, the result can be
#'   represented in a closed form (see the vignette for more details), which is
#'   what is returned.
#' @references 
#' Inferring Markov Chains: Bayesian Estimation, Model Comparison, Entropy Rate, 
#' and Out-of-Class Modeling, Christopher C. Strelioff, James P.
#' Crutchfield, Alfred Hubler, Santa Fe Institute
#' 
#' Yalamanchi SB, Spedicato GA (2015). Bayesian Inference of First Order Markov 
#' Chains. R package version 0.2.5
#' 
#' @author Sai Bhargav Yalamanchi
#' @seealso \code{\link{markovchainFit}}
#' @examples
#' sequence<- c("a", "b", "a", "a", "a", "a", "b", "a", "b", "a", "b", "a", "a", 
#'              "b", "b", "b", "a")
#' hyperMatrix<-matrix(c(1, 2, 1, 4), nrow = 2,dimnames=list(c("a","b"),c("a","b")))
#' predProb <- predictiveDistribution(sequence[1:10], sequence[11:17], hyperparam =hyperMatrix )
#' hyperMatrix2<-hyperMatrix[c(2,1),c(2,1)]
#' predProb2 <- predictiveDistribution(sequence[1:10], sequence[11:17], hyperparam =hyperMatrix2 )
#' predProb2==predProb
#' @export
#' 
predictiveDistribution <- function(stringchar, newData, hyperparam = matrix()) {
    .Call(`_markovchain_predictiveDistribution`, stringchar, newData, hyperparam)
}

#' @title priorDistribution
#'
#' @description Function to evaluate the prior probability of a transition
#'   matrix. It is based on conjugate priors and therefore a Dirichlet
#'   distribution is used to model the transitions of each state.
#' @usage priorDistribution(transMatr, hyperparam = matrix())
#'
#' @param transMatr The transition matrix whose probability is the parameter of
#'   interest.
#' @param hyperparam The hyperparam matrix (optional). If not provided, a
#'   default value of 1 is assumed for each and therefore the resulting
#'   probability distribution is uniform.
#' @return The log of the probabilities for each state is returned in a numeric
#'   vector. Each number in the vector represents the probability (log) of
#'   having a probability transition vector as specified in corresponding the
#'   row of the transition matrix.
#'
#' @details The states (dimnames) of the transition matrix and the hyperparam
#'   may be in any order.
#' @references Yalamanchi SB, Spedicato GA (2015). Bayesian Inference of First
#' Order Markov Chains. R package version 0.2.5
#'
#' @author Sai Bhargav Yalamanchi, Giorgio Spedicato
#'
#' @note This function can be used in conjunction with inferHyperparam. For
#'   example, if the user has a prior data set and a prior transition matrix,
#'   he can infer the hyperparameters using inferHyperparam and then compute
#'   the probability of their prior matrix using the inferred hyperparameters
#'   with priorDistribution.
#' @seealso \code{\link{predictiveDistribution}}, \code{\link{inferHyperparam}}
#' 
#' @examples
#' priorDistribution(matrix(c(0.5, 0.5, 0.5, 0.5), 
#'                   nrow = 2, 
#'                   dimnames = list(c("a", "b"), c("a", "b"))), 
#'                   matrix(c(2, 2, 2, 2), 
#'                   nrow = 2, 
#'                   dimnames = list(c("a", "b"), c("a", "b"))))
#' @export
priorDistribution <- function(transMatr, hyperparam = matrix()) {
    .Call(`_markovchain_priorDistribution`, transMatr, hyperparam)
}

.hittingProbabilitiesRcpp <- function(object) {
    .Call(`_markovchain_hittingProbabilities`, object)
}

.canonicFormRcpp <- function(obj) {
    .Call(`_markovchain_canonicForm`, obj)
}

.steadyStatesRcpp <- function(obj) {
    .Call(`_markovchain_steadyStates`, obj)
}

.absorbingStatesRcpp <- function(obj) {
    .Call(`_markovchain_absorbingStates`, obj)
}

.isIrreducibleRcpp <- function(obj) {
    .Call(`_markovchain_isIrreducible`, obj)
}

.isRegularRcpp <- function(obj) {
    .Call(`_markovchain_isRegular`, obj)
}

.meanAbsorptionTimeRcpp <- function(obj) {
    .Call(`_markovchain_meanAbsorptionTime`, obj)
}

.absorptionProbabilitiesRcpp <- function(obj) {
    .Call(`_markovchain_absorptionProbabilities`, obj)
}

.meanFirstPassageTimeRcpp <- function(obj, destination) {
    .Call(`_markovchain_meanFirstPassageTime`, obj, destination)
}

.meanRecurrenceTimeRcpp <- function(obj) {
    .Call(`_markovchain_meanRecurrenceTime`, obj)
}

.minNumVisitsRcpp <- function(obj) {
    .Call(`_markovchain_meanNumVisits`, obj)
}

.isProbability <- function(prob) {
    .Call(`_markovchain_isProb`, prob)
}

.isStochasticMatrix <- function(m, byrow) {
    .Call(`_markovchain_isStochasticMatrix`, m, byrow)
}

.isProbabilityVector <- function(prob) {
    .Call(`_markovchain_isProbVector`, prob)
}

.testthatIsAccesibleRcpp <- function(obj) {
    .Call(`_markovchain_checkIsAccesibleMethod`, obj)
}

.approxEqualMatricesRcpp <- function(a, b) {
    .Call(`_markovchain_approxEqual`, a, b)
}

.testthatIsPartitionRcpp <- function(commClasses, states) {
    .Call(`_markovchain_isPartition`, commClasses, states)
}

.testthatAreHittingRcpp <- function(probs, hitting, byrow) {
    .Call(`_markovchain_areHittingProbabilities`, probs, hitting, byrow)
}

.testthatAreMeanNumVisitsRcpp <- function(probs, numVisits, hitting, byrow) {
    .Call(`_markovchain_areMeanNumVisits`, probs, numVisits, hitting, byrow)
}

.testthatRecurrentHittingRcpp <- function(recurrentClasses, hitting, states, byrow) {
    .Call(`_markovchain_recurrentHitting`, recurrentClasses, hitting, states, byrow)
}

.testthatHittingAreOneRcpp <- function(matrix) {
    .Call(`_markovchain_hittingProbsAreOne`, matrix)
}

.testthatAbsorbingAreRecurrentClassRcpp <- function(absorbingStates, recurrentClasses) {
    .Call(`_markovchain_absorbingAreRecurrentClass`, absorbingStates, recurrentClasses)
}
spedygiorgio/markovchain documentation built on Feb. 29, 2024, 3:01 p.m.