| Type: | Package |
| Title: | Easy Handling Discrete Time Markov Chains |
| Version: | 1.2.1 |
| Maintainer: | Giorgio Alfredo Spedicato <spedicato_giorgio@yahoo.it> |
| Description: | Functions and S4 classes to create, manage and analyse discrete time Markov chains. Includes probabilistic analysis of chain structure (state classification, hitting times, stationary distributions, spectral and mixing diagnostics), statistical inference (maximum likelihood and Bayesian estimation, tests of the Markov property, homogeneity, stationarity and order, simulation), higher-order and multivariate chains, state aggregation, and import/export to JSON, YAML and CSV. Basic support for continuous time Markov chains is also provided; some of these functions depend on the suggested 'ctmcd' package. See Spedicato (2017) <doi:10.32614/RJ-2017-036>. |
| License: | MIT + file LICENSE |
| Depends: | R (≥ 4.4.0), Matrix (≥ 1.5-0), methods |
| Imports: | igraph (≥ 1.0.0), expm, stats4, parallel, Rcpp (≥ 1.0.2), RcppParallel, utils, stats, grDevices |
| Suggests: | knitr, testthat, diagram, DiagrammeR, ggplot2 (≥ 3.4.0), msm, Rsolnp, rmarkdown, ctmcd, bookdown, rticles, MCMCpack, microbenchmark, quarto, jsonlite, yaml, xml2, quadprog |
| Enhances: | etm |
| VignetteBuilder: | rmarkdown, knitr, bookdown, rticles, quarto |
| LinkingTo: | Rcpp, RcppParallel, RcppArmadillo (≥ 0.9.600.4.0) |
| SystemRequirements: | GNU make, Quarto |
| LazyLoad: | yes |
| ByteCompile: | yes |
| Encoding: | UTF-8 |
| BugReports: | https://github.com/spedygiorgio/markovchain/issues |
| URL: | https://github.com/spedygiorgio/markovchain/ |
| NeedsCompilation: | yes |
| Config/roxygen2/version: | 8.1.1 |
| Packaged: | 2026-11-22 20:40:16 UTC; Utente |
| Author: | Giorgio Alfredo Spedicato
|
| Repository: | CRAN |
| Date/Publication: | 2026-11-22 23:00:09 UTC |
Easy Handling Discrete Time Markov Chains
Description
The package contains classes and method to create and manage (plot, print, export for example) discrete time Markov chains (DTMC). In addition it provide functions to perform statistical (fitting and drawing random variates) and probabilistic (analysis of DTMC proprieties) analysis
Author(s)
Giorgio Alfredo Spedicato Maintainer: Giorgio Alfredo Spedicato spedicato_giorgio@yahoo.it
References
Discrete-Time Markov Models, Bremaud, Springer 1999
See Also
Useful links:
Report bugs at https://github.com/spedygiorgio/markovchain/issues
Examples
# create some markov chains
statesNames=c("a","b")
mcA<-new("markovchain", transitionMatrix=matrix(c(0.7,0.3,0.1,0.9),byrow=TRUE,
nrow=2, dimnames=list(statesNames,statesNames)))
statesNames=c("a","b","c")
mcB<-new("markovchain", states=statesNames, transitionMatrix=
matrix(c(0.2,0.5,0.3,0,1,0,0.1,0.8,0.1), nrow=3,
byrow=TRUE, dimnames=list(statesNames, statesNames)))
statesNames=c("a","b","c","d")
matrice<-matrix(c(0.25,0.75,0,0,0.4,0.6,0,0,0,0,0.1,0.9,0,0,0.7,0.3), nrow=4, byrow=TRUE)
mcC<-new("markovchain", states=statesNames, transitionMatrix=matrice)
mcD<-new("markovchain", transitionMatrix=matrix(c(0,1,0,1), nrow=2,byrow=TRUE))
#operations with S4 methods
mcA^2
steadyStates(mcB)
absorbingStates(mcB)
markovchainSequence(n=20, markovchain=mcC, include=TRUE)
Standardize statistical inference results to R's htest convention.
Description
Standardize statistical inference results to R's htest convention.
Usage
.asHtest(result, method, data.name)
Expected hitting time of a state in a continuous time Markov chain
Description
Expected time for a continuous time Markov chain started in
state i to reach state j for the first time.
Usage
ExpectedTime(C, i, j, useRCpp = TRUE)
Arguments
C |
A |
i, j |
Indices (positions in |
useRCpp |
Logical: solve the linear system in C++ (default) or with
|
Details
The expected hitting times m_k of j from the states
k \ne j solve \sum_{l \ne j} Q_{kl} m_l = -1 (Norris 1997,
Section 3.3). Every state other than j must have a positive exit
rate, otherwise an error is given; the times are finite only if j is
reachable from every state, otherwise the system is singular.
Value
A number, the expected hitting time of j from i (0 if
i == j).
Author(s)
Vandit Jain
References
Norris, J. R. (1997). Markov Chains. Cambridge University Press.
See Also
Other continuous time Markov chains:
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
rctmc(),
transition2Generator()
Examples
states <- c("a", "b", "c", "d")
gen <- matrix(c(-1, 1/2, 1/2, 0,
1/4, -1/2, 0, 1/4,
1/6, 0, -1/3, 1/6,
0, 0, 0, 0), nrow = 4, byrow = TRUE,
dimnames = list(states, states))
ctmc <- new("ctmc", states = states, byrow = TRUE, generator = gen,
name = "testctmc")
ExpectedTime(ctmc, 1, 4) # from "a" to the absorbing state "d"
Higher order Markov Chains class
Description
The S4 class that describes HigherOrderMarkovChain objects.
Absorption probabilities
Description
Computes the absorption probability from each transient state to each recurrent one (i.e. the (i, j) entry or (j, i), in a stochastic matrix by columns, represents the probability that the first not transient state we can go from the transient state i is j (and therefore we are going to be absorbed in the communicating recurrent class of j)
Usage
absorptionProbabilities(object)
Arguments
object |
the markovchain object |
Value
A named vector with the expected number of steps to go from a transient state to any of the recurrent ones
Author(s)
Ignacio Cordón
References
C. M. Grinstead and J. L. Snell. Introduction to Probability. American Mathematical Soc., 2012.
See Also
Other first passage and hitting:
committorAB(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
m <- matrix(c(1/2, 1/2, 0,
1/2, 1/2, 0,
0, 1/2, 1/2), ncol = 3, byrow = TRUE)
mc <- new("markovchain", states = letters[1:3], transitionMatrix = m)
absorptionProbabilities(mc)
Aggregate a Markov chain's state space by Kullback-Leibler minimization
Description
Reduces the state space of a finite, irreducible, aperiodic Markov chain
to k macro-states by the spectral-theoretic method of Deng, Mehta
and Meyn (2011): the macro-chain returned is the one whose "lifted"
behavior (each macro-state visit standing in for its micro-states,
weighted by their share of the stationary distribution) is closest, in
Kullback-Leibler divergence rate, to the original chain.
Usage
aggregateStates(
object,
k = NULL,
method = c("adaptive", "spectral-bottom-up", "spectral-top-down")
)
## S4 method for signature 'markovchain'
aggregateStates(
object,
k = NULL,
method = c("adaptive", "spectral-bottom-up", "spectral-top-down")
)
Arguments
object |
A |
k |
The number of macro-states to reduce to, an integer between 2
and the number of states minus 1. The default, |
method |
One of |
Details
This targets the same problem as autoLump, but by a
different and more principled route: autoLump clusters the
leading eigenvectors with k-means (a generic, randomized heuristic,
fixed here to a deterministic seed only for reproducibility), while
aggregateStates greedily minimizes the actual information-theoretic
quantity that measures how much the aggregation distorts the chain's
dynamics.
When is the divergence exactly zero? Not simply whenever
object is strongly lumpable with respect to partition in
the sense of is.lumpable. Strong lumpability only requires
that, for every pair of macro-states, all micro-states in the same source
macro-state have the same total probability of moving to the
destination macro-state; it says nothing about how that total is split
among the destination macro-state's own members. The Kullback-Leibler
divergence used here is sensitive to exactly that split: it is zero (up
to rounding) only when every source state distributes its outgoing
probability across a destination macro-state's members in the same
proportions – those of the stationary distribution restricted to that
macro-state – regardless of which source state it is. This is a
genuinely stronger condition, and a strongly lumpable chain need not
satisfy it: the classical Land of Oz weather chain (see the package
vignette), lumped into Bad_Weather = {rainy, snowy} and
Nice_Weather = {nice}, is strongly lumpable, and
aggregateStates correctly recovers that exact partition as optimal
and reproduces lump's aggregated transition matrix, but its
divergence is strictly positive, because rainy and snowy
split their probability between rainy and snowy themselves
differently from one another.
Both methods require the chain to be irreducible (for a unique, strictly
positive stationary distribution) and aperiodic (the internal averaging
step used by "spectral-top-down" to re-estimate a working
stationary distribution as macro-states are merged assumes convergence,
which is not guaranteed for a periodic chain). Use
lazyChain first to remove periodicity if needed.
Value
A named list:
partitionA named list of character vectors giving the original state names belonging to each macro-state, suitable for passing to
lumporis.lumpable. Unlike PyDTMC, which only labels the reduced chain's states generically (e.g."ASBU1"), this traces every macro-state back to the original states it stands for.aggregatedChainThe reduced
markovchainobject, row-stochastic, with states named afterpartition.klDivergenceThe Kullback-Leibler divergence rate (in bits) between
objectand the liftedaggregatedChain. It is zero (up to rounding) when every source state splits its outgoing probability among a destination macro-state's members in the same proportions – those of the stationary distribution restricted to that macro-state – regardless of the source; this is stronger than the Kemeny-Snell strong lumpability checked byis.lumpable, which only requires the macro-to-macro totals to agree across sources (see Details).methodThe method actually used, after resolving
"adaptive".kThe number of macro-states actually used, after resolving an automatic
NULL.
References
Deng, K., Mehta, P. G. and Meyn, S. P. (2011). Optimal Kullback-Leibler Aggregation via Spectral Theory of Markov Chains. IEEE Transactions on Automatic Control, 56(12). doi:10.1109/TAC.2011.2141350
Fill, J. A. (1991). Eigenvalue bounds on convergence to stationarity for nonreversible Markov chains, with an application to the exclusion process. The Annals of Applied Probability, 1(1). doi:10.1214/aoap/1177005981
See Also
autoLump, lump,
is.lumpable, closestReversible
Examples
# A chain aggregated into two macro-states {a,b}/{c,d} where, in addition
# to being strongly lumpable, "a" and "b" also split their probability
# *within* each destination block identically (0.1/0.1 and 0.4/0.4): this
# stronger property is what makes the divergence exactly zero (see
# Details for a lumpable-but-nonzero counterexample).
statesNames <- c("a", "b", "c", "d")
P <- matrix(c(0.1, 0.1, 0.4, 0.4,
0.1, 0.1, 0.4, 0.4,
0.3, 0.3, 0.2, 0.2,
0.3, 0.3, 0.2, 0.2), byrow = TRUE, nrow = 4,
dimnames = list(statesNames, statesNames))
mc <- new("markovchain", states = statesNames, transitionMatrix = P)
result <- aggregateStates(mc, k = 2)
result$partition
result$klDivergence # zero up to rounding
Test independence of consecutive states of an empirical sequence
Description
Tests the null hypothesis that consecutive observations are independent,
P(X_{t+1} = j \mid X_t = i) = P(X_{t+1} = j) for all i, j,
against the alternative of a first-order Markov chain. This is the
classical test of Anderson and Goodman (1957): a chi-squared (or
likelihood-ratio) test of independence applied to the table of observed
one-step transition counts, whose rows are the state at time t and
whose columns are the state at time t + 1.
Usage
assessIndependence(sequence, method = c("Pearson", "G"), verbose = TRUE)
Arguments
sequence |
An empirical sequence of states (at least three observations, without missing values). |
method |
Test statistic: |
verbose |
Should test results be printed? |
Details
Only states actually observed as a departure state (rows) or as an arrival
state (columns) contribute to the degrees of freedom, which are
(r - 1)(c - 1) for r such rows and c such columns. When
r or c is 1 (for instance a constant sequence) the test is not
defined: the degrees of freedom are 0 and the p-value is NA.
The statistic is asymptotic and, as for any chi-squared test on a table of counts, unreliable when many expected counts are small (say below 5). Successive transitions overlap (each observation is the arrival state of one transition and the departure state of the next); this is the standard treatment of the Anderson-Goodman test and is asymptotically valid under the null hypothesis.
Value
An htest object, returned invisibly, with the additional
components observed (transition counts, rows are departure states) and
expected (counts expected under independence).
References
Anderson, T. W. and Goodman, L. A. (1957). Statistical inference about Markov chains. The Annals of Mathematical Statistics, 28(1), 89–110.
See Also
verifyMarkovProperty, assessOrder,
assessStationarity
Examples
# an independent sequence: the test should not reject
set.seed(1)
iid <- sample(c("a", "b", "c"), 500, replace = TRUE)
assessIndependence(iid)
# a strongly dependent (Markov) sequence: the test rejects
mc <- new("markovchain", states = c("a", "b"),
transitionMatrix = matrix(c(0.9, 0.1, 0.2, 0.8), nrow = 2, byrow = TRUE))
dep <- rmarkovchain(500, mc, t0 = "a")
assessIndependence(dep, method = "G")
Aggregate a Markov chain by spectral clustering
Description
Finds a partition of the states into k blocks by k-means
clustering of the states on the right eigenvectors of the k
eigenvalues of largest modulus, then aggregates the chain over it with
lump(force = TRUE). States that the slow modes of the chain
do not distinguish (metastable groups) end up in the same block.
Usage
autoLump(object, k)
## S4 method for signature 'markovchain'
autoLump(object, k)
Arguments
object |
A |
k |
Number of blocks, an integer between 2 and the number of states minus 1. |
Details
This is a heuristic for approximate (metastable) aggregation, not
a test of exact lumpability: check the result with is.lumpable(), or
use aggregateStates() for the aggregation that minimizes the
Kullback-Leibler divergence rate. The k-means clustering is run with a
fixed seed and 10 starts, so the result is reproducible; the random
number stream of the session is left unchanged.
Value
A list with partition, a named list of the states of each block
("Macro_1", "Macro_2", ...), and lumped_chain, the aggregated
markovchain object.
See Also
Other state aggregation:
is.lumpable(),
lump()
Examples
# two groups of states that rarely communicate
statesNames <- c("a", "b", "c", "d")
P <- matrix(c(0.6, 0.38, 0.01, 0.01,
0.3, 0.68, 0.01, 0.01,
0.01, 0.01, 0.5, 0.48,
0.01, 0.01, 0.4, 0.58), nrow = 4, byrow = TRUE,
dimnames = list(statesNames, statesNames))
mc <- new("markovchain", states = statesNames, transitionMatrix = P)
autoLump(mc, k = 2)
Plot a Markov chain with ggplot2
Description
Creates a ggplot2 representation of a discrete-time Markov chain. Nodes are states and directed edges represent transitions with positive probability. Communicating classes are shown with different node fills.
Usage
autoplot.markovchain(
object,
threshold = 0,
show_probabilities = TRUE,
digits = 2,
node_size = 6,
edge_width = 1,
type = c("graph", "eigenvalues", "flow", "comparison"),
steps = 20,
initial = NULL,
other = NULL,
what = c("transition", "stationary"),
...
)
Arguments
object |
An object of class |
threshold |
Minimum transition probability to display. Defaults to 0. |
show_probabilities |
Logical; whether to label edges with transition
probabilities. Defaults to |
digits |
Number of digits used to format transition probabilities. |
node_size |
Size of state nodes in the ggplot2 plot. |
edge_width |
Minimum width multiplier for transition edges. |
type |
Type of plot: |
steps |
Number of steps of the |
initial |
Initial distribution of the |
other |
For |
what |
For |
... |
Currently unused, reserved for future extensions. |
Value
A ggplot object.
Examples
if (requireNamespace("ggplot2", quietly = TRUE)) {
weather <- matrix(c(0.7, 0.2, 0.1,
0.3, 0.4, 0.3,
0.2, 0.45, 0.35),
nrow = 3, byrow = TRUE,
dimnames = list(c("sunny", "cloudy", "rain"),
c("sunny", "cloudy", "rain")))
mc <- new("markovchain", states = rownames(weather),
transitionMatrix = weather, name = "Weather")
ggplot2::autoplot(mc)
ggplot2::autoplot(mc, type = "eigenvalues")
ggplot2::autoplot(mc, type = "flow", steps = 10, initial = "rain")
# compare with a "stickier" version of the same chain
sticky <- lazyChain(mc, alpha = 0.5)
sticky@name <- "Lazy weather"
ggplot2::autoplot(mc, type = "comparison", other = sticky)
ggplot2::autoplot(mc, type = "comparison", other = sticky,
what = "stationary")
}
Build a birth-death Markov chain
Description
Constructs a markovchain object for a birth-death process: a chain
on linearly ordered states 1,2,\ldots,n that, from any state, can
only move to itself or to an immediately adjacent state.
Usage
birthDeath(p, q, states = NULL)
Arguments
p |
A numeric vector of length |
q |
A numeric vector of length |
states |
An optional character vector of |
Details
Why p and q have length n-1, not n.
Every birth-death transition is a move between two adjacent states, and
there are exactly n-1 adjacent pairs among n linearly ordered
states: p[i]/q[i] unambiguously describe the pair
(i,i+1). This sidesteps a common source of confusion in this
construction, namely what to do with a stray "birth probability of the
top state" or "death probability of the bottom state" – quantities
that do not correspond to any actual transition, since there is no state
n+1 to be born into or state 0 to die into. Some
implementations accept two length-n vectors and quietly renormalize
every row so that any such leftover probability mass is redistributed
among the transitions that do exist; birthDeath() instead makes
the n-1 genuine transition probabilities the only inputs, so there
is no leftover mass to (silently) dispose of in the first place.
Every row's diagonal entry is determined by the requirement that the row
sums to 1, so p and q alone fully determine P:
no separate "staying" probability is accepted or needed. p+q is
allowed to reach 1 for an interior state (no staying probability
there), but each element of p and q must itself lie in
[0,1] and p[i]+q[i] for the shared index i need not be
checked against 1 the way it would for a single state's own two
probabilities, since p[i] leaves state i while q[i]
leaves state i+1: the actual per-state constraint,
p_i+q_{i-1}\le 1, is checked directly on the assembled diagonal.
The two boundary states 1 and n are reflecting only in the
weak sense that no birth/death carries them outside \{1,\ldots,n\}
– they still generally have a positive probability of staying put
(1-p_1 and 1-q_{n-1} respectively) rather than being forced
to bounce back, unlike gamblersRuin's absorbing ends or
toBoundedChain's explicit reflecting condition, which can
be applied afterwards to force deterministic bouncing or absorption at
the ends of any chain, including one built here.
Value
A new, row-stochastic markovchain object on n
states, with transition matrix
P_{ii}=1-p_i-q_{i-1},\quad P_{i,i+1}=p_i,\quad P_{i,i-1}=q_{i-1}
(boundary terms q_0 and p_n are understood to not exist,
i.e. P_{11}=1-p_1 and P_{nn}=1-q_{n-1}).
See Also
gamblersRuin, toBoundedChain,
urnModel
Examples
# A simple 4-state birth-death chain with constant birth/death rates.
bd <- birthDeath(p = c(0.3, 0.4, 0.5), q = c(0.2, 0.3, 0.1))
bd
rowSums(bd@transitionMatrix)
Mobility between income quartiles
Description
This table show mobility between income quartiles for father and sons for the 1970 cohort born
Usage
data(blanden)
Format
An object of class table with 4 rows and 4 columns.
Details
The rows represent fathers' income quartile when the son is aged 16, whilst the columns represent sons' income quartiles when he is aged 30 (in 2000).
Source
Personal reworking
References
Jo Blanden, Paul Gregg and Stephen Machin, Intergenerational Mobility in Europe and North America, Center for Economic Performances (2005)
Examples
data(blanden)
mobilityMc<-as(blanden, "markovchain")
Bootstrap confidence intervals for properties of an estimated chain
Description
Estimates a Markov chain from one or more observed sequences and gives bootstrap standard errors and confidence intervals for properties of the chain, such as the second largest eigenvalue modulus, the spectral gap, the relaxation time or the mixing time, which the corresponding functions return as point values only.
Usage
bootstrapProperties(
data,
statistics = c("slem", "spectralGap", "relaxationTime", "mixingTime"),
nboot = 1000L,
method = c("multinomial", "parametric"),
level = 0.95,
type = c("percentile", "basic"),
possibleStates = character(),
epsilon = 0.25,
seed = NULL
)
Arguments
data |
An observed sequence (character, factor or numeric vector),
a list of independent sequences, or a square matrix of transition counts
with the states as row and column names (only with
|
statistics |
Either a character vector of built-in statistics, among
|
nboot |
A single integer of at least |
method |
How the replicates are drawn: |
level |
The confidence level, a single number in |
type |
The kind of interval: |
possibleStates |
Optional character vector of states to include even if they are not observed. Every state must be left at least once in the data, otherwise its transition probabilities cannot be estimated. |
epsilon |
The total variation threshold of |
seed |
An optional whole number. When given, the replicates are drawn
after |
Details
The chain is estimated by maximum likelihood, \hat P_{ij} =
n_{ij}/n_i. With method = "multinomial" a replicate draws, for
every state i, the counts (n^*_{i1}, \ldots, n^*_{ir}) from a
multinomial distribution with n_i trials and probabilities
\hat P_{i\cdot}, and re-estimates P^*_{ij} = n^*_{ij}/n_i. This
is the conditional bootstrap of Basawa et al. (1990), valid for finite
ergodic chains, which keeps the number of visits to each state fixed. With
method = "parametric" a replicate simulates a new path of each
observed length from \hat P, as in Kulperger and Prakasa Rao
(1989); the numbers of visits then vary too, and a replicate in which some
state is never left cannot be estimated and counts as a failure. The
parametric version is slower but closer to the actual sampling scheme of a
single path.
When all the statistics are among "slem", "spectralGap",
"relaxationTime" and "mixingTime", the replicates are
computed in C++, with one eigen-decomposition per replicate; otherwise each
replicate is turned into a markovchain object and the statistics are
evaluated in R. The results are the same either way, and the random draws
come from R's generator, so set.seed and seed control them.
The percentile interval is formed by the (1-\code{level})/2 and
(1+\code{level})/2 quantiles of the replicates; the basic interval
reflects them around the estimate, 2\hat\theta - q_{1-\alpha/2} and
2\hat\theta - q_{\alpha/2}.
Some care is needed in reading the results. The SLEM and the spectral gap are not smooth functions of the matrix where the second largest eigenvalue modulus is reached by more than one eigenvalue, the mixing time is an integer, and replicates of a chain with rare transitions may be reducible or periodic, in which case some statistics fail; the bootstrap distribution of all of them can be skewed. The intervals are therefore approximate, and their coverage should be checked by simulation for the case at hand, as done in the package's vignette. The asymptotic theory of these estimators is developed by Hsu et al. (2019) for the spectral gap of reversible chains.
Value
An object of class "markovchainBootstrap", a list with:
estimateThe statistics of the estimated chain.
ciA matrix with one row per statistic and the lower and upper limits of the interval.
se,biasBootstrap standard errors and bias estimates (mean of the replicates minus the estimate).
failuresFor each statistic, the number of replicates for which it could not be computed (they are left out of the intervals).
replicatesThe
nbootby statistics matrix of bootstrap values.chainThe estimated
markovchain.countsThe matrix of observed transition counts.
method,type,level,nbootThe settings used.
References
Basawa, I. V., Green, T. A., McCormick, W. P. and Taylor, R. L. (1990). Asymptotic bootstrap validity for finite Markov chains. Communications in Statistics - Theory and Methods, 19(4), 1493-1510.
Kulperger, R. J. and Prakasa Rao, B. L. S. (1989). Bootstrapping a finite state Markov chain. Sankhya, Series A, 51(2), 178-191.
Hsu, D., Kontorovich, A., Levin, D. A., Peres, Y., Szepesvari, C. and Wolfer, G. (2019). Mixing time estimation in reversible Markov chains from a single sample path. The Annals of Applied Probability, 29(4), 2439-2480. doi:10.1214/18-AAP1457
See Also
slem, spectralGap,
relaxationTime, mixingTime,
markovchainFit (whose method = "bootstrap" gives
bootstrap standard errors of the transition probabilities themselves)
Examples
data(rain)
set.seed(1)
boot <- bootstrapProperties(rain$rain, nboot = 200)
boot
boot$ci
# any function of the chain, here the stationary probability of no rain
bootstrapProperties(rain$rain, nboot = 200, seed = 2,
statistics = list(dry = function(mc) steadyStates(mc)[1, "0"]))
Closest reversible approximation of a Markov chain
Description
Finds the Markov chain closest to a given one among the reversible
chains, either with respect to a fixed stationary distribution or, with
stationaryDistribution = "free", over all stationary
distributions.
Usage
closestReversible(
object,
stationaryDistribution = NULL,
tolerance = sqrt(.Machine$double.eps),
norm = c("pi", "frobenius"),
nstart = 5L
)
## S4 method for signature 'markovchain'
closestReversible(
object,
stationaryDistribution = NULL,
tolerance = sqrt(.Machine$double.eps),
norm = c("pi", "frobenius"),
nstart = 5L
)
Arguments
object |
A |
stationaryDistribution |
Optional numeric vector giving the
stationary distribution |
tolerance |
A single finite non-negative number, used when checking
that a supplied |
norm |
The distance to minimize: |
nstart |
With |
Details
For a row-stochastic transition matrix P with stationary
distribution \pi, define the time reversal P^* by
P^*_{ij} = \frac{\pi_j P_{ji}}{\pi_i}.
P^* is the transition matrix of the same chain run backwards in
time, and P is reversible exactly when P = P^*. With the
default norm = "pi" the approximation returned is the
additive reversibilization
R = \tfrac{1}{2}\left(P + P^*\right),
which is stochastic, non-negative, and reversible with respect to the
same \pi (see Details). With norm = "frobenius" it is the
reversible chain nearest to P in the plain Frobenius norm, the
problem solved by Nielsen and Weber (2015).
In what sense is this the closest chain? With the default
norm = "pi", work in the space
\ell^2(\pi) of functions on the states with inner product
\langle f,g\rangle_\pi=\sum_i \pi_i f_i g_i. Reversible chains are
exactly the self-adjoint operators on that space, and they form a linear
subspace. The matching Hilbert-Schmidt inner product on operators is
\langle A,B\rangle_\pi = \sum_{i,j} \frac{\pi_i}{\pi_j} A_{ij}B_{ij},
\qquad \|A\|_\pi^2 = \sum_{i,j} \frac{\pi_i}{\pi_j} A_{ij}^2,
and A \mapsto A^* is an isometric involution for it. The orthogonal
projection onto the fixed points of such an involution is the average of
a point and its image, so R=(P+P^*)/2 is the closest
\pi-reversible matrix to P in \|\cdot\|_\pi. The
stochastic and non-negativity constraints come for free: P^* has
row sums \sum_j \pi_j P_{ji}/\pi_i = (\pi P)_i/\pi_i = 1 because
\pi is stationary, and both P and P^* are
non-negative, so the minimizer over the subspace already lies in the set
of transition matrices and no constrained optimization is needed.
The Frobenius norm with a fixed \pi. With
norm = "frobenius" the result minimizes
\|P - R\|_F^2 = \sum_{i,j}(P_{ij} - R_{ij})^2 over the transition
matrices that satisfy detailed balance
\pi_i R_{ij} = \pi_j R_{ji}. This is the problem of Nielsen and
Weber (2015). Since A\mapsto A^* is not an isometry of this norm,
the additive reversibilization is generally not its solution, and the
non-negativity constraints can be active. The problem is a convex
quadratic program: with the n(n-1)/2 entries R_{ij}, i<j,
as unknowns, R_{ji} = \pi_i R_{ij}/\pi_j and
R_{ii} = 1 - \sum_{j\ne i}R_{ij}, the objective is strictly convex
and the constraints are R_{ij} \ge 0 and R_{ii} \ge 0. It
is solved exactly by the dual active-set method of
quadprog::solve.QP, in O(n^6) time, which is practical up to
about 50 states. \pi need not be stationary for P; the
result is reversible, hence stationary, with respect to it.
Letting \pi vary. With
stationaryDistribution = "free" the minimization is over all
reversible chains, whatever their stationary distribution. Every such
chain can be written as R_{ij} = S_{ij}/\sum_k S_{ik} with
S symmetric and non-negative (S_{ij} = \pi_i R_{ij}, the
probability flows), so the problem becomes a smooth minimization over
S \ge 0, solved with optim(method = "L-BFGS-B") and the
analytic gradient. The set of reversible chains is not convex, so the
result is a local minimum: nstart starting points are tried, and
each local solution is polished by solving the convex problem above at its
own \pi, which can only decrease the distance. Nielsen and Weber
(2015) keep \pi fixed; this extension is specific to the package.
The distance found is never larger than the one obtained with the
stationary distribution of object.
What this function does not do. With norm = "pi" the
minimization holds \pi fixed: the \pi-weighted norm itself
depends on \pi, so letting it vary is only offered for the
Frobenius norm. Also, the weighted Frobenius norm of PyDTMC's
closest_reversible(weighted = TRUE) is not offered. PyDTMC solves
the unweighted problem with an iterative solver, whose solutions agree with
the ones here to about 10^{-5} and have a slightly larger distance.
Properties worth knowing. R has the same stationary
distribution \pi as P, and it preserves the support pattern
in the symmetrized sense: R_{ij}>0 whenever P_{ij}>0 or
P_{ji}>0. It may therefore allow transitions the original chain
forbids, which is inherent to making a chain reversible rather than a
defect of this construction. If object is already reversible,
R=P and distance is zero (up to rounding). Fill (1991)
introduces this construction, alongside the multiplicative
reversibilization PP^*, which is a different object and is not
computed here.
Only irreducibility is required, not aperiodicity. Irreducibility
guarantees both a unique \pi and \pi_i>0 for every state, so
the division defining P^* is always safe.
The implementation calls steadyStates at most once and is
then O(n^2) in time and memory for a dense n-state
transition matrix; no eigendecomposition or optimization is involved.
Value
A named list with five elements:
chainThe approximating
markovchainobjectR, with the same states and the same row/column-stochastic storage convention asobject.stationaryDistributionThe
\piwith respect to whichRis reversible, as a named numeric vector: the one used or, with"free", the one found.distanceThe distance actually minimized:
\|P-R\|_\pifornorm = "pi",\|P-R\|_Ffornorm = "frobenius"(see Details).frobeniusDistanceThe plain Frobenius distance
\|P-R\|_F, reported for convenience; withnorm = "pi"it is not the quantity being minimized.normThe norm used.
With stationaryDistribution = "free" a sixth element,
starts, gives for each starting point the Frobenius distance
reached.
References
Fill, J. A. (1991). Eigenvalue bounds on convergence to stationarity for nonreversible Markov chains, with an application to the exclusion process. The Annals of Applied Probability, 1(1). doi:10.1214/aoap/1177005981
Nielsen, A. and Weber, M. (2015). Computing the nearest reversible Markov chain. Numerical Linear Algebra with Applications, 22. doi:10.1002/nla.1967
See Also
is.reversible, steadyStates,
is.irreducible
Examples
# A directed 3-cycle is as far from reversible as a chain gets: it only
# ever moves one way round. Its closest reversible approximation is the
# undirected random walk on the same triangle.
statesNames <- c("a", "b", "c")
cycle3 <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0, 1, 0,
0, 0, 1,
1, 0, 0), byrow = TRUE, nrow = 3,
dimnames = list(statesNames, statesNames)))
is.reversible(cycle3)
approximation <- closestReversible(cycle3)
approximation$chain
is.reversible(approximation$chain)
approximation$distance
# The nearest reversible chain in the Frobenius norm (needs quadprog),
# first with the stationary distribution held fixed, then free.
if (requireNamespace("quadprog", quietly = TRUE)) {
P <- new("markovchain", states = letters[1:4], transitionMatrix = matrix(
c(0.1, 0.6, 0.2, 0.1, 0.05, 0.15, 0.7, 0.1,
0.3, 0.05, 0.25, 0.4, 0.5, 0.2, 0.1, 0.2), 4, byrow = TRUE,
dimnames = list(letters[1:4], letters[1:4])))
closestReversible(P)$frobeniusDistance
closestReversible(P, norm = "frobenius")$distance
set.seed(1)
free <- closestReversible(P, "free", norm = "frobenius")
free$distance
free$stationaryDistribution
}
Committor probabilities
Description
Probability that a Markov chain hits the set of states A
before the set B (the committor function), from every initial state or
from one.
Usage
committorAB(object, A, B, p = 1)
Arguments
object |
A |
A, B |
Disjoint sets of states, given as indices (positions in
|
p |
Optional index of the initial state. If omitted, the probabilities for all initial states are returned. |
Details
The committor q solves the linear system
q_i = \sum_j P_{ij} q_j for the states outside A \cup B,
with q = 1 on A and q = 0 on B. The system has a unique
solution when A or B can be reached from every state.
Value
A numeric vector with the probability for each initial state, or
a single number if p is given.
See Also
Other first passage and hitting:
absorptionProbabilities(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
transMatr <- matrix(c(0, 0, 0, 1, 0.5,
0.5, 0, 0, 0, 0,
0.5, 0, 0, 0, 0,
0, 0.2, 0.4, 0, 0,
0, 0.8, 0.6, 0, 0.5), nrow = 5)
object <- new("markovchain", states = c("a", "b", "c", "d", "e"),
transitionMatrix = transMatr)
# probability of reaching "e" before "c", from each state
committorAB(object, 5, 3)
committorAB(object, 5, 3, p = 1)
Compare two Markov chains
Description
Computes distances and divergences between two Markov chains on the same states and, when the chains are given as observed sequences, tests whether the sequences come from the same chain.
Usage
compareChains(
x,
y,
base = exp(1),
test = c("G", "Pearson", "simulation", "none"),
...
)
Arguments
x, y |
Two |
base |
The base of the logarithm used by the divergences (default
|
test |
For sequences, the test of equality of the two transition
matrices passed to |
... |
Further arguments for |
Details
The measures that depend on a stationary distribution
(weightedTotalVariation, stationary, rateXY,
rateYX) are NA when the chain concerned has more than one.
The row-wise measures and their names follow PyDTMC's
calculate_transition_distance,
calculate_transition_divergence and
calculate_stationary_distance, which give the same values.
For two sequences the test is that of Anderson and Goodman (1957) and
Kullback, Kupperman and Ku (1962): the hypothesis that both come from the
same chain, against different transition matrices. Each sequence is
treated as one sample; for several sequences per group, or for counts,
call verifyHomogeneity directly.
Value
An object of class "markovchainComparison", a list with:
distancesA named vector:
totalVariation, the largest row-wise total variation distance\max_i \frac12\sum_j |P_{ij} - Q_{ij}|;weightedTotalVariation, the same row distances averaged with the stationary distribution ofx;hellinger, the largest row-wise Hellinger distance\max_i \sqrt{\frac12 \sum_j (\sqrt{P_{ij}} - \sqrt{Q_{ij}})^2};frobenius,\|P - Q\|_F;maximum,\max_{i,j}|P_{ij} - Q_{ij}|; andstationary, the total variation distance between the two stationary distributions.divergencesA named vector:
rateXYandrateYX, the Kullback-Leibler divergence ratesD(P\|Q)andD(Q\|P)(seedivergenceRate);maxRowXY, the largest row-wise Kullback-Leibler divergence ofPfromQ; andjensenShannon, the largest row-wise Jensen-Shannon divergence, which is symmetric and finite.stationaryDistributionsA two-row matrix with the stationary distributions of
xandy.testFor sequences, the
htestreturned byverifyHomogeneity; otherwiseNULL.x,yThe two chains, as
markovchainobjects.
References
Anderson, T. W. and Goodman, L. A. (1957). Statistical inference about Markov chains. The Annals of Mathematical Statistics, 28(1), 89-110.
Kullback, S., Kupperman, M. and Ku, H. H. (1962). Tests for contingency tables and Markov chains. Technometrics, 4(4), 573-608.
Rached, Z., Alajaji, F. and Campbell, L. L. (2004). The Kullback-Leibler divergence rate between Markov sources. IEEE Transactions on Information Theory, 50(5), 917-921. doi:10.1109/TIT.2004.826687
See Also
divergenceRate, verifyHomogeneity,
autoplot.markovchain (type = "comparison")
Examples
s <- c("a", "b", "c")
P <- new("markovchain", states = s, transitionMatrix = matrix(
c(0.5, 0.3, 0.2, 0.1, 0.6, 0.3, 0.25, 0.25, 0.5), 3, byrow = TRUE,
dimnames = list(s, s)))
Q <- new("markovchain", states = s, transitionMatrix = matrix(
c(0.4, 0.4, 0.2, 0.2, 0.5, 0.3, 0.3, 0.1, 0.6), 3, byrow = TRUE,
dimnames = list(s, s)))
compareChains(P, Q)
# two sequences: distances between the estimated chains, and a test
set.seed(1)
x <- rmarkovchain(300, P, t0 = "a")
y <- rmarkovchain(300, Q, t0 = "a")
compareChains(x, y)
Conditional distribution of the next state
Description
Returns the distribution of the next state of a Markov chain given its current state: the row of the transition matrix of that state (its column if the chain is stored by columns).
Usage
conditionalDistribution(object, state)
Arguments
object |
A |
state |
Name of the current state. |
Value
A probability vector named by the states.
Author(s)
Giorgio Spedicato, Deepak Yadav
See Also
transitionProbability() for a single probability.
Examples
# define a markov chain
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1),nrow = 3,
byrow = TRUE, dimnames = list(statesNames, statesNames)))
conditionalDistribution(markovB, "b")
CD4 cells counts on HIV Infects between zero and six month
Description
This is the table shown in Craig and Sendi paper showing zero and six month CD4 cells count in six brakets
Usage
data(craigsendi)
Format
A 3 x 3 contingency table of counts, with rows and columns named
"0-49", "50-74" and "75-UP".
Details
Rows represent counts at the beginning, cols represent counts after six months.
Source
Estimation of the transition matrix of a discrete time Markov chain, Bruce A. Craig and Peter P. Sendi, Health Economics 11, 2002.
References
see source
Examples
data(craigsendi)
csMc<-as(craigsendi, "markovchain")
steadyStates(csMc)
Continuous time Markov chain class
Description
The S4 class of continuous time Markov chains, described by their generator (rate) matrix.
Slots
statesNames of the states, equal to the row and column names of the generator.
byrowLogical: are the rates out of each state in its row (rows sum to zero) or in its column?
generatorThe square generator matrix: non-negative off-diagonal rates, with rows (or columns) summing to zero.
nameOptional name of the chain.
Methods
- dim
signature(x = "ctmc"): method to get the size- initialize
signature(.Object = "ctmc"): initialize method- states
signature(object = "ctmc"): states method.- steadyStates
signature(object = "ctmc"): method to get the steady state vector.- plot
signature(x = "ctmc", y = "missing"): plot method forctmcobjects
Note
The validity method checks that the rows (or columns) of the generator sum to zero, rounded to the fifth decimal. If the generator has no state names, the states are named "s1", "s2", ...
References
Introduction to Stochastic Processes with Applications in the Biosciences (2013), David F. Anderson, University of Wisconsin at Madison. Sai Bhargav Yalamanchi, Giorgio Spedicato
See Also
generatorToTransitionMatrix,rctmc
Examples
energyStates <- c("sigma", "sigma_star")
byRow <- TRUE
gen <- matrix(data = c(-3, 3,
1, -1), nrow = 2,
byrow = byRow, dimnames = list(energyStates, energyStates))
molecularCTMC <- new("ctmc", states = energyStates,
byrow = byRow, generator = gen,
name = "Molecular Transition Model")
steadyStates(molecularCTMC)
plot(molecularCTMC)
Fit a continuous time Markov chain
Description
Maximum likelihood estimation of a continuous time Markov chain from one observed trajectory: the sequence of states visited and the times at which they were entered.
Maximum likelihood estimation of a continuous time Markov chain from one observed trajectory: the sequence of states visited and the times at which they were entered.
Usage
ctmcFit(data, byrow = TRUE, name = "", confidencelevel = 0.95)
Arguments
data |
A list of two vectors of equal length: the states visited (character) and the times at which they were entered (numeric, increasing, the first equal to 0). |
byrow |
Logical: return the generator, and the transition matrix of the embedded jump chain in the confidence intervals, with the rates out of each state in its row (default) or in its column? |
name |
Optional name of the fitted chain. |
confidencelevel |
Confidence level of the intervals (default 0.95). |
Details
The exit rate of state i is estimated as the number of
departures from i divided by the total time spent in i, and
the jump probabilities by the transition frequencies of the sequence of
states; the generator is their product. The interval for each rate is the
normal approximation \hat\lambda_i (1 \pm z / \sqrt{n_i}),
with n_i the number of departures from i, truncated at 0.
The exit rate of state i is estimated as the number of
departures from i divided by the total time spent in i, and
the jump probabilities by the transition frequencies of the sequence of
states; the generator is their product. The interval for each rate is the
normal approximation \hat\lambda_i (1 \pm z / \sqrt{n_i}),
with n_i the number of departures from i, truncated at 0.
Value
A list with two elements:
estimatethe fitted
ctmcobject;errorsa list with
dtmcConfidenceInterval, the confidence level and the lower and upper endpoint matrices of the transition probabilities of the embedded jump chain (as inmarkovchainFit()), andlambdaConfidenceInterval, the lower and upper endpoints of the exit rate of each state.
A list with two elements:
estimatethe fitted
ctmcobject;errorsa list with
dtmcConfidenceInterval, the confidence level and the lower and upper endpoint matrices of the transition probabilities of the embedded jump chain (as inmarkovchainFit()), andlambdaConfidenceInterval, the lower and upper endpoints of the exit rate of each state.
Author(s)
Sai Bhargav Yalamanchi
References
Yalamanchi, S. B. and Spedicato, G. A. (2015). Continuous time Markov chains. Vignette of the markovchain package.
Yalamanchi, S. B. and Spedicato, G. A. (2015). Continuous time Markov chains. Vignette of the markovchain package.
See Also
Other continuous time Markov chains:
ExpectedTime(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
rctmc(),
transition2Generator()
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))
fit <- ctmcFit(data)
fit$estimate
fit$errors$lambdaConfidenceInterval
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))
fit <- ctmcFit(data)
fit$estimate
fit$errors$lambdaConfidenceInterval
Markov chain from a Dirichlet process
Description
Generates a Markov chain whose rows are drawn from a truncated Dirichlet
process with the stick-breaking (GEM) construction, as
MarkovChain.dirichlet_process() of PyDTMC does.
Usage
dirichletChain(
n,
diffusion,
states = NULL,
diagonalBias = NULL,
shiftConcentration = FALSE,
byrow = TRUE,
seed = NULL,
name = "Dirichlet process chain"
)
Arguments
n |
The number of states, at least 2. It can be omitted when
|
diffusion |
The concentration parameter |
states |
An optional character vector of |
diagonalBias |
An optional positive number |
shiftConcentration |
If |
byrow |
Whether the transition matrix of the result is stored by rows (the default) or by columns. |
seed |
An optional whole number, as in
|
name |
The |
Details
For each row, b_1, \ldots, b_n are independent
\mathrm{Beta}(1, \alpha) draws and the weights are
w_j = b_j \prod_{k < j} (1 - b_k),
normalised to sum to one (the truncation at n states leaves out the
mass \prod_k (1 - b_k)). PyDTMC only accepts whole values of
\alpha between 1 and n; any positive value is accepted here,
since the construction is defined for every \alpha > 0.
Value
A markovchain object with n states.
References
Sethuraman, J. (1994). A constructive definition of Dirichlet priors. Statistica Sinica, 4(2), 639-650.
See Also
Examples
dirichletChain(5, diffusion = 2, seed = 1)
# a chain that tends to stay in its current state
dirichletChain(5, diffusion = 2, diagonalBias = 5, seed = 1)
Kullback-Leibler divergence rate between two Markov chains
Description
Computes the Kullback-Leibler divergence rate of a Markov chain x
from a Markov chain y on the same states: the limit of
\frac{1}{n} D(X_1,\ldots,X_n \,\|\, Y_1,\ldots,Y_n), the average
information per step for discriminating x against y.
Usage
divergenceRate(x, y, weights = NULL, base = exp(1))
Arguments
x, y |
Two |
weights |
Optional non-negative numeric vector, one entry per state
(named or in the order of |
base |
The base of the logarithm: the default |
Details
For chains with transition matrices P (of x) and Q
(of y) and with \pi the stationary distribution of P,
the divergence rate is
D(P \,\|\, Q) = \sum_i \pi_i \sum_j P_{ij} \log \frac{P_{ij}}{Q_{ij}},
which Rached, Alajaji and Campbell (2004) prove to be the limit above
for irreducible chains, whatever the initial distributions. By the
ergodic theorem it is also the almost sure limit of
\frac1n \log \frac{\Pr_P(X_1, \ldots, X_n)}{\Pr_Q(X_1, \ldots, X_n)}
along a path of x. It is zero exactly when the rows of P and
Q agree on every state of positive weight, and it is not symmetric.
With weights equal to the relative frequencies of the departure
states of a sequence, 2N D(\hat P \,\|\, Q), with N the number
of transitions, is the likelihood-ratio statistic G^2 of the
hypothesis that the sequence comes from Q (Kullback, Kupperman and
Ku 1962), as computed by verifyEmpiricalToTheoretical.
Value
A single non-negative number, Inf when x makes with
positive probability a transition that y forbids from a state of
positive weight.
References
Rached, Z., Alajaji, F. and Campbell, L. L. (2004). The Kullback-Leibler divergence rate between Markov sources. IEEE Transactions on Information Theory, 50(5), 917-921. doi:10.1109/TIT.2004.826687
Kullback, S., Kupperman, M. and Ku, H. H. (1962). Tests for contingency tables and Markov chains. Technometrics, 4(4), 573-608.
See Also
Examples
s <- c("a", "b", "c")
P <- new("markovchain", states = s, transitionMatrix = matrix(
c(0.5, 0.3, 0.2, 0.1, 0.6, 0.3, 0.25, 0.25, 0.5), 3, byrow = TRUE,
dimnames = list(s, s)))
Q <- new("markovchain", states = s, transitionMatrix = matrix(
c(0.4, 0.4, 0.2, 0.2, 0.5, 0.3, 0.3, 0.1, 0.6), 3, byrow = TRUE,
dimnames = list(s, s)))
divergenceRate(P, Q)
divergenceRate(Q, P) # not symmetric
divergenceRate(P, P)
Entropy rate of a Markov chain
Description
Computes the entropy rate of a finite, irreducible discrete-time Markov chain from its stationary distribution and transition matrix.
Usage
entropyRate(object, base = 2)
## S4 method for signature 'markovchain'
entropyRate(object, base = 2)
Arguments
object |
A |
base |
A finite numeric scalar strictly greater than one. The default,
|
Details
For a row-stochastic transition matrix P and stationary distribution
\pi, the entropy rate is
H = -\sum_i \pi_i \sum_j p_{ij}\log_b(p_{ij}),
with zero-probability transitions contributing zero by continuity.
For a stationary first-order Markov chain, the entropy rate equals the
conditional entropy H(X_{t+1}\mid X_t). Irreducibility guarantees a
unique stationary distribution; aperiodicity is not required.
Reducible chains may admit multiple stationary distributions and therefore different entropy rates. This method rejects them rather than silently selecting one stationary distribution.
Transitions with probability zero are ignored, implementing the standard
convention 0\log(0)=0 without evaluating log(0).
The stationary-distribution computation dominates the running time. Once
the stationary distribution is available, evaluating the entropy rate takes
O(n^2) time and O(n^2) temporary memory for a dense n-state
transition matrix.
Value
A non-negative numeric scalar containing the entropy rate in units
determined by base.
References
Cover, T. M. and Thomas, J. A. (2006). Elements of Information Theory, 2nd edition. Wiley.
Strelioff, C. C., Crutchfield, J. P. and Huebler, A. W. (2007). Inferring Markov chains: Bayesian estimation, model comparison, entropy rate, and out-of-class modeling. Physical Review E, 76, 011106.
See Also
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
entropyRate(mc)
entropyRate(mc, base = exp(1))
Expected cumulative reward of a Markov chain
Description
Expected total reward collected by a Markov chain over the
times 0, 1, \dots, n, for every initial state, when state i
pays rewards[i] at each visit.
Usage
expectedRewards(markovchain, n, rewards)
Arguments
markovchain |
A |
n |
Number of steps, a non-negative integer. |
rewards |
Numeric vector with the reward of each state, in the order
of |
Details
The values solve the dynamic programming recursion
v_0 = r, v_k = r + P v_{k-1} (Gallager 2013, Section 3.5),
so that v_n = \sum_{k=0}^{n} P^k r.
Value
A numeric vector with one value per initial state.
Author(s)
Vandit Jain
References
Gallager, R. G. (2013). Stochastic Processes: Theory for Applications. Cambridge University Press.
See Also
Other rewards:
expectedRewardsBeforeHittingA()
Examples
transMatr <- matrix(c(0.99, 0.01, 0.01, 0.99), nrow = 2, byrow = TRUE)
simpleMc <- new("markovchain", states = c("a", "b"),
transitionMatrix = transMatr)
expectedRewards(simpleMc, 1, c(0, 1))
Expected reward collected before hitting a set of states
Description
Expected total reward collected by a Markov chain started in
state at the steps 1, \dots, n it spends outside the set A
before entering it, when state i pays rewards[i] at each visit.
Usage
expectedRewardsBeforeHittingA(markovchain, A, state, rewards, n)
Arguments
markovchain |
A |
A |
Names of the states of the target set. |
state |
Name of the initial state, not in |
rewards |
Numeric vector with the reward of each state, in the order
of |
n |
Number of steps, a non-negative integer. |
Details
With Q the transition matrix restricted to the states
outside A, the value is \sum_{k=1}^{n} (Q^k r)_{s}, with
s the initial state: the reward of the initial state at time 0 is
not included.
Value
A number, the expected reward.
Author(s)
Sai Bhargav Yalamanchi, Vandit Jain
See Also
Other rewards:
expectedRewards()
Examples
transMatr <- matrix(c(0.5, 0.3, 0.2,
0.2, 0.5, 0.3,
0, 0, 1), nrow = 3, byrow = TRUE)
mc <- new("markovchain", states = c("a", "b", "c"),
transitionMatrix = transMatr)
# reward 1 per step spent in "a" or "b" before absorption in "c"
expectedRewardsBeforeHittingA(mc, A = "c", state = "a",
rewards = c(1, 1, 0), n = 100)
First passage time distribution
Description
Distribution of the first passage times of a Markov chain
started in state: for every state j and step k, the
probability that the chain enters j for the first time at step
k.
Usage
firstPassage(object, state, n)
Arguments
object |
A |
state |
Name of the initial state. |
n |
Number of steps, a positive integer. |
Details
For j equal to state the probabilities are those of the
first return. The algorithm follows the Matlab listings of Feres.
Value
A matrix with n rows (steps 1, \dots, n) and one column per
state: entry (k, j) is the probability that the first passage to
j happens at step k. The column sums are at most one; the
remainder is the probability of a first passage after step n, or never.
Author(s)
Giorgio Spedicato
References
Feres, R. Notes for Math 450: Matlab listings for Markov chains. Washington University in St. Louis.
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
simpleMc <- new("markovchain", states = c("a", "b"),
transitionMatrix = matrix(c(0.4, 0.6, 0.3, 0.7),
nrow = 2, byrow = TRUE))
firstPassage(simpleMc, "b", 20)
First passage time distribution of a set of states
Description
Distribution of the first passage time into a set of states:
the probability that a Markov chain started in state enters set for
the first time at step k = 1, \dots, n.
Usage
firstPassageMultiple(object, state, set, n)
Arguments
object |
A |
state |
Name of the initial state. |
set |
Names of the states of the target set. |
n |
Number of steps, a positive integer. |
Value
A one-column matrix (column "set") with n rows: row k
is the probability that the first passage into set happens at step
k.
Author(s)
Vandit Jain
References
Feres, R. Notes for Math 450: Matlab listings for Markov chains. Washington University in St. Louis.
Gallager, R. G. 6.262 Discrete Stochastic Processes, course notes, chapter 5. MIT OpenCourseWare.
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3,
0, 1, 0,
0.1, 0.8, 0.1), nrow = 3, byrow = TRUE,
dimnames = list(statesNames, statesNames)))
firstPassageMultiple(markovB, "a", c("b", "c"), 4)
Markov chain approximating a continuous transition kernel by quadrature
Description
Builds a finite-state Markov chain from a transition density (or any
non-negative transition kernel) of a continuous-state process, by
evaluating the kernel at the nodes of a quadrature rule (the Nystrom
method). It is the counterpart of PyDTMC's fit_function.
Usage
fitFunction(
f,
size,
quadrature = c("gauss-legendre", "gauss-chebyshev", "fejer", "gauss-hermite",
"trapezoid", "simpson", "midpoint"),
interval = c(0, 1),
mean = 0,
sd = 1,
states = NULL,
name = NULL
)
Arguments
f |
A function of two arguments, |
size |
A single integer of at least |
quadrature |
The quadrature rule, one of |
interval |
A numeric vector |
mean, sd |
Mean and standard deviation of the normal distribution
that defines the nodes of |
states |
Optional character vector of |
name |
Optional name of the chain. |
Details
With nodes y_1, \ldots, y_n and weights w_1, \ldots, w_n of
a rule for \int g(y)\,dy, the transition matrix is
P_{ij} = \frac{w_j f(y_i, y_j)}{\sum_{k} w_k f(y_i, y_k)}.
If f(x, \cdot) is the transition density of the continuous
process, \sum_j P_{ij} h(y_j) approximates
E[h(Y_{t+1}) \mid Y_t = y_i] for every smooth h, and the
normalization corrects the mass lost outside the nodes. The kernel does
not need to integrate to one: only its values at the nodes matter.
The rules, all with positive weights:
-
"gauss-legendre": Gauss-Legendre nodes, exact for polynomials of degree2n - 1. A good default for smooth kernels on a bounded interval. -
"gauss-chebyshev": Gauss-Chebyshev nodes of the first kind,t_k = -\cos((2k - 1)\pi / (2n))on[-1, 1], with the weights(\pi/n)\sqrt{1 - t_k^2}of a plain integral. It is exact forg(t) = q(t)/\sqrt{1 - t^2}withqa polynomial of degree2n - 1, so it suits kernels with that kind of behaviour at the end points. -
"fejer": Fejer's first rule, the same Chebyshev nodes with the weights that integrate exactly every polynomial of degreen - 1. This is the rule that PyDTMC calls"gauss-chebyshev". -
"gauss-hermite": Gauss-Hermite nodes for the normal distributionN(\code{mean}, \code{sd}^2), for processes on the real line. The weights of the plain integral are the probability weights divided by the normal density at the nodes. With an AR(1) density this is the method of Tauchen and Hussey (1991); seetauchenHussey. -
"trapezoid"and"simpson": equally spaced nodes including the end points; Simpson's rule needs an oddsize. -
"midpoint": the centres ofsizeequal cells.
Newton-Cotes rules of high order are not offered, because their weights become negative and would give negative probabilities.
A row whose kernel values are all zero at the nodes (the process cannot reach any node from there) stops the function with an error: PyDTMC replaces such a row with a uniform distribution, which invents transitions; here the interval, the number of nodes or the kernel should be changed instead.
For the same kernel, interval and number of nodes, the
"gauss-legendre", "fejer", "trapezoid" and
"simpson" rules give the same matrices as PyDTMC 10.0.0
("gauss-legendre", "gauss-chebyshev",
"trapezoid-rule" and "simpson-rule"); PyDTMC's midpoint
rule ("newton-cotes") ignores the lower end of the interval.
Value
A list with three elements:
chainThe
markovchainobject (row-stochastic).statesThe nodes, a numeric vector named by the states, in the order of the states of
chain.weightsThe quadrature weights for the plain integral
\int g(y)\,dy \approx \sum_j w_j g(y_j), named by the states.
References
Tauchen, G. and Hussey, R. (1991). Quadrature-based methods for obtaining approximate solutions to nonlinear asset pricing models. Econometrica, 59(2), 371-396. doi:10.2307/2938261
Golub, G. H. and Welsch, J. H. (1969). Calculation of Gauss quadrature rules. Mathematics of Computation, 23(106), 221-230. doi:10.2307/2004418
Fejer, L. (1933). Mechanische Quadraturen mit positiven Cotesschen Zahlen. Mathematische Zeitschrift, 37, 287-309. doi:10.1007/BF01474575
See Also
tauchenHussey, tauchen,
rouwenhorst
Examples
# A process on [0, 1] that moves towards 0.6 times its current value,
# with a Gaussian kernel truncated to the interval.
kernel <- function(x, y) dnorm(y, mean = 0.6 * x + 0.2, sd = 0.15)
out <- fitFunction(kernel, size = 7, interval = c(0, 1))
out$chain
# expected next value from each node, against the continuous one
cbind(chain = as.numeric(out$chain@transitionMatrix %*% out$states),
target = 0.6 * out$states + 0.2)
Fit a higher order multivariate Markov chain
Description
Fits the higher order multivariate Markov chain of Ching, Ng
and Fung (2008) to several categorical sequences observed together: the
next state of each sequence depends on the last order states of all the
sequences, through a weighted sum of lag-specific transition matrices.
Usage
fitHighOrderMultivarMC(seqMat, order = 2, Norm = 2)
Arguments
seqMat |
A matrix or data frame with one categorical sequence per column, all of the same length; numeric or factor values are taken as state labels (compared as character strings). |
order |
Order of the chain (default 2). |
Norm |
Norm used to estimate the weights (default 2): the weights minimize this norm of the difference between the state frequencies of each sequence and their image under the model, as in Ching et al. (2008). The minimization needs the suggested package Rsolnp. |
Value
An hommc object. If Rsolnp is not
available, NULL with a warning.
Author(s)
Giorgio Spedicato, Deepak Yadav
References
Ching, W.-K., Ng, M. K. and Fung, E. S. (2008). Higher-order multivariate Markov chains and their applications. Linear Algebra and its Applications 428(2-3), 492-507. doi:10.1016/j.laa.2007.05.021
See Also
predictHommc() to simulate from the fit.
Other higher order chains:
fitHigherOrder(),
predictHommc()
Examples
data <- matrix(c("2", "1", "3", "3", "4", "3", "2", "1", "3", "3", "2", "1",
"2", "4", "4", "4", "4", "2", "3", "3", "1", "4", "3", "3"),
ncol = 2)
if (requireNamespace("Rsolnp", quietly = TRUE)) {
fitHighOrderMultivarMC(data, order = 2, Norm = 2)
}
Fit a higher order Markov chain
Description
Fits the higher order Markov chain of Ching et al., in which
the distribution of the next state is a weighted mixture of the empirical
lag-i transition matrices, i = 1, \dots, order.
seq2freqProb() returns the state frequencies of a sequence and
seq2matHigh() its empirical lag-order transition matrix, the building
blocks of the model.
Usage
fitHigherOrder(sequence, order = 2, method = c("mle", "lsq"))
seq2freqProb(sequence)
seq2matHigh(sequence, order)
Arguments
sequence |
The sequence of states: a character vector, or a vector coercible to character (numbers and factors are matched to the states as character strings), without missing values. A list of such vectors is taken as independent sequences, see Details. |
order |
Order of the chain, a positive integer smaller than the
sequence length; for |
method |
How the weights |
Details
The fitted model expresses the distribution of the next state as
the mixture \sum_{i=1}^{k} \lambda_i Q_i x_{t-i} of the empirical
lag-i transition matrices Q_i (see seq2matHigh), with
weights \lambda_i \ge 0 summing to one. The matrices Q_i
are the same for both methods; only the weights differ.
method = "lsq" (the default before version 1.2.1, and the only method
before the argument existed) chooses \lambda to minimize the squared distance
between the stationary distribution and its image under the mixture, as in
Ching et al.; it needs the Rsolnp package and returns NULL
with a warning if it is unavailable. This criterion is weak: each lag
matrix maps the empirical distribution onto itself up to end effects,
Q_i X \approx X with an error of order i/n, so the
objective is nearly flat in \lambda and the weights it returns can
be unstable from one sample to another. It remains available, to
reproduce earlier results or the method of Ching et al., but it is no
longer the default.
method = "mle" (the default) chooses \lambda to maximize the
log-likelihood \sum_{t=k+1}^{n} \log \sum_i \lambda_i Q_i[x_t,
x_{t-i}] of the observations a model of order k can predict. For
fixed Q_i the problem is concave, so the maximum is global, and it
is solved, without Rsolnp, by Newton's method with an active set
on the simplex, which stops when the Karush-Kuhn-Tucker conditions of
the maximum hold within 10^{-10} (in practice after 3 to 10
iterations, also when some weights are 0). The weights are therefore
those that give the highest value of higherOrderLogLik for
the same observations. (Up to version 1.2 the EM
algorithm for mixture weights was used: near a weight equal to 0, or
when the lags carry nearly the same information, it converged very
slowly and could stop visibly short of the maximum.)
They are maximum likelihood estimates conditional on the empirical
matrices Q_i, which are not re-estimated: this is not the maximum
likelihood estimator of the mixture with free matrices, in which the
weights are in general not identifiable (a common distribution can be
moved from \lambda_j Q_j to \lambda_i Q_i without changing
any transition probability), so the weights should not be read as the
relative importance of the lags beyond this conditional sense. Note
that this is not the mixture transition distribution model of Raftery
(1985), in which a single matrix is shared by all lags and is estimated
together with the weights; that model is fitted by fitMTD.
With a list of sequences the lag matrices Q_i and the state
frequencies are computed from the counts pooled over the sequences, which
are treated as independent: no pair of observations spans two sequences,
and a sequence with no more than order states contributes to the
frequencies only. The weights are then estimated as for a single sequence,
from the observations that a model of that order can predict in every
sequence.
A warning is given when the sequence supplies no more observations than the
model has free parameters (the number used by higherOrderLogLik),
since the weights are then essentially undetermined.
Value
fitHigherOrder(): a list with lambda, the weights of the lags;
Q, the list of the lag-i transition matrices (column-stochastic:
entry [j, k] is the probability of moving to j from k);
and X, the state frequencies. With method = "lsq", NULL with a
warning if Rsolnp is not available.
seq2freqProb(): the vector of state frequencies, named by state.
seq2matHigh(): the column-stochastic lag-order transition matrix (a
state never observed as a departure state gets a uniform column).
Author(s)
Giorgio Spedicato, Tae Seung Kang
References
Ching, W. K., Huang, X., Ng, M. K., & Siu, T. K. (2013). Higher-order markov chains. In Markov Chains (pp. 141-176). Springer US.
Ching, W.-K., Ng, M. K. and Fung, E. S. (2008). Higher-order multivariate Markov chains and their applications. Linear Algebra and its Applications 428(2-3), 492-507. doi:10.1016/j.laa.2007.05.021
Raftery, A. E. (1985). A model for high-order Markov chains. Journal of the Royal Statistical Society, Series B, 47(3), 528-539.
See Also
higherOrderLogLik(), higherOrderPredict(), fitMTD(),
selectOrder()
Other higher order chains:
fitHighOrderMultivarMC(),
predictHommc()
Examples
sequence<-c("a", "a", "b", "b", "a", "c", "b", "a", "b", "c", "a", "b",
"c", "a", "b", "c", "a", "b", "a", "b")
# weights by maximum likelihood (the default, no Rsolnp needed)
fit <- fitHigherOrder(sequence, order = 2)
fit$lambda
# weights by least squares on the stationary distribution, as in Ching et al.
fitHigherOrder(sequence, order = 2, method = "lsq")
higherOrderLogLik(sequence, fit)$logLik
Fit a mixture transition distribution (MTD) model
Description
Estimates by maximum likelihood the mixture transition
distribution model of Raftery (1985) for a high-order Markov chain: the
probability of the next state is a weighted mixture of the
contributions of the last order states, all governed by the same
transition matrix.
Usage
fitMTD(
sequence,
order = 2,
start = NULL,
nstart = 1,
tol = 1e-10,
maxit = 10000L,
model = c("MTD", "MTDg"),
accelerate = FALSE,
se = FALSE,
negativeWeights = FALSE
)
Arguments
sequence |
An empirical sequence of states (a character vector, or a vector coercible to character), without missing values, or a list of such vectors, taken as independent sequences (see Details). |
order |
Order of the model, a positive integer smaller than the length of the sequence. |
start |
Index of the first observation entering the likelihood, at
least |
nstart |
|
tol |
Convergence tolerance on the relative change of the log-likelihood between two iterations. |
maxit |
Maximum number of EM iterations for each starting point (EM
steps, if |
model |
|
accelerate |
Logical: speed up the EM algorithm with the SQUAREM
scheme of Varadhan and Roland (2008)? The default |
se |
Logical: compute standard errors (see Details)? |
negativeWeights |
Logical: allow negative lag weights, as in Raftery
(1985)? Only for |
Details
For an order k the model is
P(X_t = j \mid X_{t-1} = i_1, \dots, X_{t-k} = i_k) =
\sum_{g=1}^{k} \lambda_g\, q_{i_g j},
where Q = (q_{ij}) is an r \times r transition matrix (rows
are departure states) and the lag weights \lambda_g sum to one.
It needs r(r-1) + k - 1 parameters instead of the
r^k (r-1) of a fully parameterized Markov chain of order k,
which makes high orders practicable (Raftery, 1985; Berchtold and
Raftery, 2002). This is different from the model fitted by
fitHigherOrder, which mixes a different empirical matrix
for each lag and does not estimate them jointly with the weights.
By default the weights are constrained to be non-negative, as in most
applications of the model (see below for negative weights). Under this
constraint the likelihood is maximized by
the EM algorithm of Lebre and Bourguignon (2008), in which the latent
variable is the lag that generated each observation; it is implemented in
C++. Every iteration increases the likelihood, but the likelihood of the
MTD model can have several local maxima (Berchtold, 2001). The models of
order 1, \dots, order are therefore fitted in turn on the
same observations, and order k is started from equal weights with
the transition matrix of all lags pooled, and from the fit of order
k - 1 extended with a zero and with a small positive weight for the
new lag. The first of these extensions has the likelihood of order
k - 1, so the likelihood returned never decreases with the order,
as it must for nested models. nstart - 1 further random starting
points can be added for the requested order; they are drawn at random, so
call set.seed beforehand for reproducible results. The fit
with the highest likelihood is returned.
The likelihood is conditional on the observations before start:
it is the product of the transition probabilities of x_t for
t = start, \dots, n. The default,
order + 1, uses every observation an order-order model can
predict. To compare models of different orders (or with the Markov chains
of fitHigherOrder via higherOrderLogLik) use
the same start for all, for instance 1 + the largest order;
Berchtold and Raftery (2002) condition on the first 14 observations,
i.e. start = 15.
With a list of sequences the likelihood is the product over the
sequences: each contributes the observations from start to its end,
the earlier ones being only used as conditioning states, no lag spans two
sequences, and a sequence with fewer than start states is not used
(apart from the state frequencies X). order must be smaller
than the length of the longest sequence.
A state that never occurs in a conditioning position (for instance one
observed only at the end of the sequence) does not enter the likelihood;
its row of Q is not identified and is returned as uniform.
A warning is given when the number of observations entering the likelihood does not exceed the number of free parameters.
With model = "MTDg" (Berchtold, 2001; Lebre and Bourguignon, 2008)
the probability of the next state is \sum_g \lambda_g\, q^{(g)}_{i_g j}
with a transition matrix Q_g for each lag. It has
(r-1)(1 + k(r-1)) free parameters, the number of the models of
fitHigherOrder, of which it is the maximum likelihood
version: there the matrices are the empirical ones and only the weights are
fitted. The EM algorithm is the same; order k is started from the
MTD fit of the same order, from the empirical matrices with the best
weights for them, and from the fit of order k - 1, so its likelihood
is never below those of model = "MTD" and of the
method = "mle" fit of fitHigherOrder, nor of
lower orders. The row of Q_g of a state never seen at lag g is
returned as uniform.
The weights and matrices of the MTDg model are not identified: since the
probabilities only depend on the products A_g = \lambda_g Q_g, adding
\epsilon times the same probability vector to every row of A_1
and subtracting it from every row of A_2 changes \lambda_1,
\lambda_2, Q_1 and Q_2 but no transition probability.
The maximum is therefore attained on a set of dimension up to
(k - 1) r, of which the values returned are one point; only the
transition probabilities (and the likelihood) are determined, and
npar counts the identified parameters. The lag weights of an MTDg
fit should not be interpreted as the importance of the lags.
With negativeWeights = TRUE (model "MTD" only) the weights may
be negative, as in Raftery's (1985) original formulation, provided every
transition probability \sum_g \lambda_g q_{i_g j} lies in
[0, 1] for all the combinations of departure states i_g: for
each arrival state j, \min_i q_{ij} times the sum of the positive
weights must not be below \max_i q_{ij} times the sum of the absolute
negative weights (Raftery, 1985). The EM algorithm does not apply, and the
likelihood is maximized by block coordinate ascent in the spirit of
Berchtold (2001): in the weights and in each row of Q in turn, mass is
moved from the entry with the smallest to the one with the largest partial
derivative, by the step that maximizes the likelihood along that direction
within the feasible region. Order k starts from the fit with
non-negative weights of the same order and from the fit of order
k - 1 with a zero weight for the new lag, so its likelihood is never
below either of them; for the requested order it also starts with each lag
in turn given a negative weight. The likelihood has several local maxima,
and this is slower than the EM algorithm. iterations then counts the
sweeps of the ascent at the requested order. Unidentified rows of Q are
returned as uniform, or as the mean of the other rows if a uniform row
would violate the condition.
With se = TRUE the standard errors are those of the observed
information at the maximum, by the delta method, obtained in closed form
with the entries of each probability vector (the weights and each row of
Q) summing to one. Entries that are on the boundary of the parameter
space (below 10^{-4}) are held fixed, as in the usual treatment of
constrained maxima, and have NA; a warning is given if a weight is
among them, since then the standard errors of the others are conditional on
that weight being zero (with negative weights allowed, if Raftery's
condition is binding). Standard errors are also given for the transition
probabilities of every history observed in the data. For the MTDg model
only these are available, the weights and matrices not being identified;
they are computed with a generalized inverse of the information, which
gives the same variance for any identified quantity. All are asymptotic,
and approximate in small samples or with sparse Q.
AIC and BIC use the number of free parameters r(r-1) + k - 1, and
BIC the number of observations entering the likelihood. Berchtold and
Raftery (2002) do not count the elements of Q estimated as exactly
zero; their BIC can be obtained by subtracting the number of those
elements from npar.
Value
A list with components
lambda |
the estimated lag weights, named |
estimate |
a |
Q |
a list of |
X |
the relative frequencies of the states in |
logLikelihood, npar, AIC, BIC, nobs |
maximized log-likelihood, number of free parameters, information criteria and number of observations entering the likelihood |
order, start |
as used in the fit |
iterations, converged |
EM iterations (sweeps of the coordinate
ascent with |
model |
|
negativeWeights |
as used in the fit |
se |
only if |
References
Raftery, A. E. (1985). A model for high-order Markov chains. Journal of the Royal Statistical Society, Series B, 47(3), 528-539.
Berchtold, A. (2001). Estimation in the mixture transition distribution model. Journal of Time Series Analysis, 22(4), 379-397.
Berchtold, A. and Raftery, A. E. (2002). The mixture transition distribution model for high-order Markov chains and non-Gaussian time series. Statistical Science, 17(3), 328-356.
Lebre, S. and Bourguignon, P.-Y. (2008). An EM algorithm for estimation in the mixture transition distribution model. Journal of Statistical Computation and Simulation, 78(1), 1-15.
Varadhan, R. and Roland, C. (2008). Simple and globally convergent methods for accelerating the convergence of any EM algorithm. Scandinavian Journal of Statistics, 35(2), 335-353.
See Also
fitHigherOrder, higherOrderLogLik,
higherOrderPredict, markovchainFit
Examples
# hourly wind directions at Koeberg (Berchtold and Raftery, 2002)
wind <- read.csv(system.file("extdata", "koeberg_wind.csv",
package = "markovchain"))$state
fit <- fitMTD(wind, order = 2, start = 15)
fit$lambda
fit$estimate
c(logLik = fit$logLikelihood, BIC = fit$BIC)
# several starting points guard against local maxima
set.seed(1)
fitMTD(wind, order = 3, start = 15, nstart = 5)$logLikelihood
# standard errors, and the model with a matrix for each lag
fit2 <- fitMTD(wind, order = 2, start = 15, se = TRUE)
fit2$se$lambda
fitMTD(wind, order = 2, start = 15, model = "MTDg")$logLikelihood
Generator matrix estimated from a matrix of transition frequencies
Description
Estimates the generator of a continuous time Markov chain from
the empirical transition matrix observed over a period of length t,
with the regularization algorithms of Kreinin and Sidelnikova (2001),
which return a valid generator (non-negative off-diagonal rates, rows
summing to zero) even when the matrix logarithm of P is not one. The
computation is done by the suggested package ctmcd.
Usage
freq2Generator(P, t = 1, method = "QO", logmethod = "Eigen")
Arguments
P |
Matrix of relative transition frequencies over the period: a square matrix whose rows sum to one. |
t |
Length of the observation period, a positive number (default 1). |
method |
Regularization algorithm: |
logmethod |
Method of the matrix logarithm used by ctmcd
(default |
Value
The estimated generator, a matrix with the dimensions and dimnames
of P; NULL, with a warning, if ctmcd is not installed.
References
Kreinin, A. and Sidelnikova, M. (2001). Regularization algorithms for transition matrices. Algo Research Quarterly 4(1), 23-40.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
rctmc(),
transition2Generator()
Examples
counts <- matrix(c(150, 2, 1, 1,
1, 200, 2, 1,
2, 1, 175, 1,
1, 1, 1, 150), nrow = 4, byrow = TRUE)
# relative frequencies, with the last state made absorbing
rel <- rbind((counts / rowSums(counts))[1:3, ], c(0, 0, 0, 1))
if (requireNamespace("ctmcd", quietly = TRUE)) freq2Generator(rel, 1)
# rating transitions (quasi-optimization estimate)
data(tm_abs)
tmRel <- rbind((tm_abs / rowSums(tm_abs))[1:7, ], c(rep(0, 7), 1))
if (requireNamespace("ctmcd", quietly = TRUE)) freq2Generator(tmRel, 1)
Fundamental matrix of an absorbing Markov chain
Description
Computes the fundamental matrix of a finite absorbing discrete-time Markov
chain. If Q is the transition submatrix restricted to transient
states, the fundamental matrix is
N = I + Q + Q^2 + \cdots = (I - Q)^{-1}.
The (i,j) entry is the expected number of visits to transient state
j, including the initial visit when i = j, before absorption,
when the chain starts in transient state i.
Usage
fundamentalMatrix(object)
Arguments
object |
A |
Details
For a finite absorbing chain, the state space can be reordered so that the
transition matrix has canonical form with transient block Q and an
absorbing block. The spectral radius of Q is less than one, so the
Neumann series converges and I-Q is nonsingular.
The fundamental matrix also gives the expected time to absorption through
t = N 1, where 1 is a vector of ones, and absorption
probabilities through B = N R, where R contains transition
probabilities from transient to absorbing states.
The function requires an absorbing Markov chain: at least one absorbing state must exist and every recurrent state must be absorbing. A chain with no transient states is a valid degenerate case and returns a 0-by-0 matrix.
Value
A numeric matrix containing the fundamental matrix, with transient state names as row and column names. If all states are absorbing, the result is a 0-by-0 matrix because there are no transient states.
References
Kemeny, J. G. and Snell, J. L. (1976). Finite Markov Chains. Springer.
Grinstead, C. M. and Snell, J. L. (1997). Introduction to Probability. American Mathematical Society.
See Also
absorbingStates, transientStates,
meanAbsorptionTime, absorptionProbabilities
Examples
states <- c("a", "b", "absorbed")
mc <- new("markovchain", states = states,
transitionMatrix = matrix(c(
0.5, 0.4, 0.1,
0.2, 0.6, 0.2,
0, 0, 1
), nrow = 3, byrow = TRUE,
dimnames = list(states, states)))
fundamentalMatrix(mc)
Build a gambler's ruin Markov chain
Description
Constructs the classic gambler's ruin chain: a gambler with a fortune
between 0 and upperBound wins each round (and gains one
unit) with probability prob, otherwise loses one unit; play stops
as soon as the fortune reaches 0 (ruin) or upperBound
(the gambler's target).
Usage
gamblersRuin(upperBound, prob, states = NULL)
Arguments
upperBound |
A single positive integer: the fortune at which the
gambler stops (having won). The chain has |
prob |
A single number in |
states |
An optional character vector of |
Details
This is the special case of birthDeath with constant birth
probability prob and constant death probability 1-prob at
every interior state, together forced to be absorbing rather than
merely reflecting at the two ends – which is why it is provided as its
own constructor rather than expressed purely in terms of
birthDeath(), which cannot produce absorbing boundaries by itself
(see toBoundedChain for turning any chain's ends
absorbing or reflecting after construction).
With prob != 0.5, the classical ruin probability of reaching
0 before upperBound, starting from fortune i, is
P(\text{ruin}\mid X_0=i) =
\frac{\left(\frac{1-\code{prob}}{\code{prob}}\right)^{i} -
\left(\frac{1-\code{prob}}{\code{prob}}\right)^{\code{upperBound}}}
{1-\left(\frac{1-\code{prob}}{\code{prob}}\right)^{\code{upperBound}}},
and i/\code{upperBound} when prob = 0.5; this is a standard
textbook result (see Norris (1998), Section 1.3) and is not itself
computed by this function, but can be read off from
absorptionProbabilities applied to the returned chain.
Value
A new, row-stochastic markovchain object with
upperBound + 1 states. States "0" and
as.character(upperBound) are absorbing; every interior state
i has P_{i,i+1}=\code{prob} and P_{i,i-1}=1-\code{prob}.
References
Norris, J. R. (1998). Markov Chains. Cambridge University Press.
See Also
birthDeath, absorptionProbabilities,
toBoundedChain
Examples
ruin <- gamblersRuin(upperBound = 5, prob = 0.4)
ruin
absorbingStates(ruin)
Transition matrix of the embedded jump chain
Description
Computes, from the generator Q of a continuous time
Markov chain, the transition matrix of its embedded (jump) chain: the
probability of jumping from i to j \ne i is
-Q_{ij} / Q_{ii}.
Usage
generatorToTransitionMatrix(gen, byrow = TRUE)
Arguments
gen |
A generator matrix: non-negative off-diagonal rates, with rows
(or columns, if |
byrow |
Logical: are the rates out of each state in its row (default) or in its column? The result has the same orientation. |
Value
The transition matrix of the embedded chain, with the dimnames of
gen. A state with zero exit rate (absorbing) gets probability 1 of
staying where it is.
Author(s)
Sai Bhargav Yalamanchi
References
Anderson, D. F. (2013). Introduction to Stochastic Processes with Applications in the Biosciences. University of Wisconsin at Madison.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
rctmc(),
transition2Generator()
Examples
energyStates <- c("sigma", "sigma_star")
gen <- matrix(c(-3, 3, 1, -1), nrow = 2, byrow = TRUE,
dimnames = list(energyStates, energyStates))
generatorToTransitionMatrix(gen)
Log-likelihood, deviance and information criteria of a higher order Markov chain
Description
Evaluates the log-likelihood of an empirical sequence under the
higher order Markov chain returned by fitHigherOrder, and
derives the deviance, AIC and BIC, so that models of different orders can
be compared.
Usage
higherOrderLogLik(sequence, fit = NULL, order = 2, start = NULL)
Arguments
sequence |
The empirical sequence of states, a character vector or a vector coercible to character (numbers and factors are matched to the states of the fit as character strings), or a list of such vectors, taken as independent sequences: the log-likelihood is then the sum over the sequences. |
fit |
The list returned by |
order |
Order of the model to fit when |
start |
Index of the first observation included in the likelihood.
Defaults to |
Details
The fitted model is the mixture-transition-distribution model of
Raftery (1985) in the form used by Ching et al.: the probability of moving
to state x_t given the past is
P(x_t \mid x_{t-1}, \dots, x_{t-k}) = \sum_{i=1}^{k} \lambda_i\, Q_i[x_t, x_{t-i}],
where Q_i is the lag-i transition matrix (see
seq2matHigh) and k is the order. The log-likelihood is
the sum of the logarithms of these probabilities over the observations
t = start, \dots, T, and the deviance is
-2 times the log-likelihood.
Two points matter when interpreting the output. First,
fitHigherOrder chooses \lambda by default
(method = "mle") to maximize this log-likelihood, conditionally on
the empirical lag matrices, for the observations a model of that order can
predict; with method = "lsq" the weights come from a least squares
fit on the stationary distribution, not from maximum likelihood, so the
value returned is the log-likelihood of the fitted model, not the
maximum attainable one. Second, a model of order k can only be evaluated from
observation k + 1 onwards; to compare orders on exactly the same data
set start to 1 + the largest order compared, otherwise the
models are evaluated on different numbers of observations and neither the
log-likelihood nor the information criteria are comparable.
The number of parameters used for AIC and BIC is the dimension of the
set of transition laws the model can represent,
(r - 1)(1 + k (r - 1)), with r the number of states: each of
the k lag matrices has r (r - 1) free probabilities and there
are k - 1 free weights, but the weights of a mixture of lag
matrices are not identifiable (a distribution common to all departure
states can be moved from \lambda_j Q_j to \lambda_i Q_i
without changing any transition probability), which removes
r (k - 1) parameters from the naive count
k\, r (r - 1) + (k - 1): for each next state the transition
probability is a sum of one term for each lag, a main-effects function of
the k past states, with 1 + k (r - 1) free coefficients.
For k = 1 both counts are r (r - 1). For a fit returned by
fitMTD, whose lags share a single matrix, it is
r (r - 1) + (k - 1).
Value
A list with components logLik, deviance, AIC,
BIC, nobs (number of observations entering the likelihood),
npar, order and start. The log-likelihood is
-Inf if an observed transition has probability zero under the model
(possible only for a sequence other than the one the model was fitted on).
References
Raftery, A. E. (1985). A model for high-order Markov chains. Journal of the Royal Statistical Society, Series B, 47(3), 528-539.
Ching, W. K., Huang, X., Ng, M. K., & Siu, T. K. (2013). Higher-order markov chains. In Markov Chains (pp. 141-176). Springer US.
See Also
fitHigherOrder, fitMTD,
higherOrderPredict
Examples
sequence <- c("a", "a", "b", "b", "a", "c", "b", "a", "b", "c", "a", "b",
"c", "a", "b", "c", "a", "b", "a", "b")
# compare orders 1 and 2 on the same observations (start = 3)
fit1 <- fitHigherOrder(sequence, order = 1)
fit2 <- fitHigherOrder(sequence, order = 2)
sapply(list(order1 = fit1, order2 = fit2), function(f)
unlist(higherOrderLogLik(sequence, f, start = 3)[c("logLik", "deviance", "AIC", "BIC")]))
Next-state probabilities and simulation for higher order Markov chains
Description
higherOrderPredict returns the distribution of the next
state given the most recent states, and higherOrderSimulate draws a
sequence of states, under a higher order model fitted by
fitHigherOrder or fitMTD.
Usage
higherOrderPredict(fit, history)
higherOrderSimulate(n, fit, t0, include.t0 = FALSE)
Arguments
fit |
The list returned by |
history |
The most recent states, oldest first: a vector of at least
|
n |
Number of states to simulate. |
t0 |
The states preceding the simulated ones, oldest first; at least
|
include.t0 |
Should |
Details
Both functions use the transition probabilities of the fitted model
of order k,
P(x_t = j \mid x_{t-1}, \dots, x_{t-k}) = \sum_{i=1}^{k} \lambda_i\, Q_i[j, x_{t-i}],
the same that enter higherOrderLogLik. For a fit returned
by fitMTD all the Q_i are the single MTD transition
matrix. Only the last k states of a history are used, the last
element being the most recent.
A model of order k needs k previous states, so t0
(and every history) must contain at least order states. The
probabilities are normalized to sum to one, which only matters when the
weights of a least squares fit sum to one up to the optimizer's tolerance.
Value
higherOrderPredict: a named vector of next-state
probabilities for a single history, or a matrix with one row per history.
higherOrderSimulate: a character vector of n states,
preceded by t0 if include.t0 = TRUE.
See Also
fitHigherOrder, fitMTD,
higherOrderLogLik, rmarkovchain
Examples
wind <- read.csv(system.file("extdata", "koeberg_wind.csv",
package = "markovchain"))$state
fit <- fitMTD(wind, order = 2)
# next wind direction after directions 1 and then 2
higherOrderPredict(fit, c(1, 2))
# several histories at once
higherOrderPredict(fit, rbind(c(1, 1), c(2, 2), c(4, 1)))
# simulate one day of hourly directions starting from the last two observed
set.seed(1)
higherOrderSimulate(24, fit, t0 = tail(wind, 2))
# the same works for fitHigherOrder()
data(rain)
fit2 <- fitHigherOrder(rain$rain, order = 2, method = "mle")
higherOrderPredict(fit2, c("0", "6+"))
Hitting probabilities of a Markov chain
Description
Given a markovchain object, this function calculates the probability of ever arriving from state i to j
Usage
hittingProbabilities(object, targets = NULL,
solver = c("direct", "bicgstab", "doubling"), tol = 1e-13, maxIter = 200)
Arguments
object |
the markovchain-class object |
targets |
optional character vector of state names: only the hitting
probabilities towards these states are computed. The default,
|
solver |
the method used to solve the linear system
|
tol |
relative residual at which the iterative solvers
( |
maxIter |
maximum number of iterations of the iterative solvers: the
number of BiCGSTAB steps, or the number of squarings of the doubled Neumann
series. A warning is raised, and the current values returned, if the
requested |
Details
On each target the states are first split by graph reachability:
a state that cannot reach the target has probability zero, and one that can
reach the target but no closed class outside it has probability one. Only
the remaining states need the linear system that solver controls, so
on chains where that split already decides every state (an irreducible
chain, for instance) all three solvers do the same negligible amount of
work. The choice matters on chains with several closed classes, i.e. on
genuine absorption probabilities.
Value
a matrix of hitting probabilities. Entry [i, j] is the
probability of ever arriving from state i to state j (the
probability of returning, after at least one transition, on the diagonal);
for a chain with byrow = FALSE the matrix is transposed, as the
transition matrix is. With targets, only the columns (rows if
byrow = FALSE) of the targets are returned, in the order given, and
they coincide with those of the full matrix.
Author(s)
Ignacio Cordón
References
R. Vélez, T. Prieto, Procesos Estocásticos, Librería UNED, 2013
H. A. van der Vorst (1992). Bi-CGSTAB: A Fast and Smoothly Converging Variant of Bi-CG for the Solution of Nonsymmetric Linear Systems. SIAM Journal on Scientific and Statistical Computing, 13(2), 631-644.
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
firstPassageMultiple(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
M <- markovchain:::zeros(5)
M[1,1] <- M[5,5] <- 1
M[2,1] <- M[2,3] <- 1/2
M[3,2] <- M[3,4] <- 1/2
M[4,2] <- M[4,5] <- 1/2
mc <- new("markovchain", transitionMatrix = M)
hittingProbabilities(mc)
# only the probabilities of ever reaching the first state
hittingProbabilities(mc, targets = "1")
# on a large sparse chain, the iterative solver avoids the dense products
hittingProbabilities(mc, targets = "1", solver = "bicgstab")
Holson data set
Description
A data set containing 1000 life histories trajectories and a categorical status (1,2,3) observed on eleven evenly spaced steps.
Usage
data(holson)
Format
A data frame with 1000 observations on the following 12 variables.
idunique id
time1observed status at i-th time
time2observed status at i-th time
time3observed status at i-th time
time4observed status at i-th time
time5observed status at i-th time
time6observed status at i-th time
time7observed status at i-th time
time8observed status at i-th time
time9observed status at i-th time
time10observed status at i-th time
time11observed status at i-th time
Details
The example can be used to fit a markovchain or a markovchainList object.
Source
Private communications
References
Private communications
Examples
data(holson)
head(holson)
Higher order multivariate Markov chain class
Description
The S4 class of the higher order multivariate Markov chains
of Ching, Ng and Fung (2008), fitted by fitHighOrderMultivarMC(): the
distribution of the next state of each of s sequences is a
weighted sum, over the sequences and the lags, of transition matrices
applied to their past states.
Slots
orderThe order of the chain (number of lags).
statesThe states, common to all the sequences.
PA three-dimensional array of
s^2timesordertransition matrices, one for each pair of sequences and lag.LambdaThe weights of the matrices in
P, in the same order.byrowLogical: are the matrices stochastic by rows (
TRUE) or by columns (FALSE, as returned byfitHighOrderMultivarMC())?nameOptional name of the object.
Author(s)
Giorgio Spedicato, Deepak Yadav
References
Ching, W.-K., Ng, M. K. and Fung, E. S. (2008). Higher-order multivariate Markov chains and their applications. Linear Algebra and its Applications 428(2-3), 492-507. doi:10.1016/j.laa.2007.05.021
Examples
statesName <- c("a", "b")
P <- array(0, dim = c(2, 2, 4), dimnames = list(statesName, statesName))
P[,,1] <- matrix(c(0, 1, 1/3, 2/3), byrow = FALSE, nrow = 2)
P[,,2] <- matrix(c(1/4, 3/4, 0, 1), byrow = FALSE, nrow = 2)
P[,,3] <- matrix(c(1, 0, 1/3, 2/3), byrow = FALSE, nrow = 2)
P[,,4] <- matrix(c(3/4, 1/4, 0, 1), byrow = FALSE, nrow = 2)
Lambda <- c(0.8, 0.2, 0.3, 0.7)
ob <- new("hommc", order = 1, states = statesName, P = P,
Lambda = Lambda, byrow = FALSE, name = "FOMMC")
An S4 class for representing Imprecise Continuous Time Markovchains
Description
An S4 class for representing Imprecise Continuous Time Markovchains
Slots
statesa vector of states present in the ICTMC model
Qmatrix representing the generator demonstrated in the form of variables
rangea matrix that stores values of range of variables
namename given to ICTMC
Identity Markov chain
Description
Builds the Markov chain whose transition matrix is the identity: every state is absorbing, so the chain never moves.
Usage
identityChain(n, states = NULL, name = "Identity chain")
Arguments
n |
The number of states. It can be omitted when |
states |
An optional character vector of |
name |
The |
Details
The chain is the neutral element of the product of transition matrices
(identityChain(n) * mc equals mc for a chain mc on
the same states) and the extreme case of lazyChain. Every
state is its own closed class, so every distribution is stationary.
Value
A markovchain object with n states.
See Also
Examples
identityChain(3)
identityChain(states = c("a", "b"))
absorbingStates(identityChain(3))
Implied timescales of a Markov chain
Description
Computes the implied relaxation timescale associated with each non-trivial eigenvalue of a finite, irreducible discrete-time Markov chain.
Usage
impliedTimescales(object)
## S4 method for signature 'markovchain'
impliedTimescales(object)
Arguments
object |
A |
Details
For a row-stochastic transition matrix P with eigenvalues
1=\lambda_1,\lambda_2,\ldots,\lambda_n (|\lambda_1| the unique
unit eigenvalue of an irreducible chain), the implied timescale of
\lambda_k, k>1, is
\tau_k = -\frac{1}{\log|\lambda_k|}
for 0<|\lambda_k|<1. Each \tau_k measures how many steps the
mode associated with \lambda_k takes to decay by a factor of
1/e; larger timescales correspond to slower-decaying, more
persistent modes.
Only irreducibility is required, not aperiodicity: this is the same
convention used by slem and spectralGap, and
it lets impliedTimescales() document periodic and boundary cases
explicitly rather than rejecting them:
If
|\lambda_k|is (numerically) exactly1– which happens for non-trivial eigenvalues of periodic chains, e.g.\lambda=-1for a 2-cycle – the corresponding mode never decays andtau_k = Infis returned. This is a boundary case of the formula above (as|\lambda|\to 1^-,\tau\to\infty) that is handled explicitly rather than by evaluating-1/\log(1), which is numerically-Infrather than the mathematically correct+Inf.If
|\lambda_k|is (numerically) exactly0, the mode decays immediately andtau_k = 0is returned.log(0)evaluates to-Infin R, so this case is already handled correctly by the formula itself and needs no special-casing.
The term "implied timescale" follows the Markov state model literature
in molecular kinetics, where it is additionally used, across chains
estimated at increasing lag times, as a self-consistency check on the
Markov (memoryless) approximation: implied timescales that are
approximately constant across lag times support the model, while ones
that drift indicate it should be revisited (see Prinz et al. (2011)).
Building such a lag-time comparison is left to the user, since it
requires re-estimating the chain at each lag: impliedTimescales()
itself only evaluates a single, already-fitted markovchain object.
The implementation calls eigen() with only.values = TRUE,
so it never computes eigenvectors. Its time complexity is
O(n^3) and its memory use is O(n^2) for a dense n-state
transition matrix. It supports both row- and column-stochastic storage.
The eigenvalues are kept in a session cache, so other spectral functions
called on the same chain do not recompute them (see
markovchainCache).
Value
A named numeric vector of length n-1 (one entry per
non-trivial eigenvalue), sorted by decreasing timescale, i.e. by
decreasing eigenvalue modulus. Names are "tau2", "tau3",
..., matching the usual eigenvalue indexing
\lambda_2,\lambda_3,\ldots in decreasing modulus. For the trivial
one-state chain, a length-zero named numeric vector is returned.
References
Swope, W. C., Pitera, J. W. and Suits, F. (2004). Describing protein folding kinetics by molecular dynamics simulations, 1: Theory. J. Phys. Chem. B, 108(21), 6571-6581.
Prinz, J.-H., Wu, H., Sarich, M., Keller, B., Senne, M., Held, M., Chodera, J. D., Schutte, C. and Noe, F. (2011). Markov models of molecular kinetics: Generation and validation. Journal of Chemical Physics, 134(17), 174105.
See Also
slem, spectralGap,
is.irreducible
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
impliedTimescales(mc)
Lower transition probability of an imprecise continuous time Markov chain
Description
For an imprecise continuous time Markov chain, whose
transition rates are only known to lie in intervals, computes the lower
probability of being in state i at time s, as a function of the state
at time t (Krak et al. 2017).
Usage
impreciseProbabilityatT(C, i, t = 0, s, error = 10^-3, useRCpp = TRUE)
Arguments
C |
An |
i |
Index (position in the states of |
t |
Initial time (default 0). |
s |
Final time, larger than |
error |
Maximum approximation error (default 0.001). |
useRCpp |
Logical: use the C++ implementation (default)? It requires
|
Details
The lower transition operator is approximated by
n steps g \leftarrow g + \delta \underline{Q} g, with
\delta = (s - t) / n and n chosen so that the error is below
error, starting from the indicator of state i; \underline{Q}
takes, in each row, the smaller of the values given by the two extremes of
the interval of rates.
Value
A numeric vector with one element per state x: the lower
probability that the chain is in state i at time s given that it is in
x at time t. With degenerate intervals (range equal to 1) it is
column i of \exp((s - t) Q), up to error.
Author(s)
Vandit Jain
References
Krak, T., De Bock, J. and Siebes, A. (2017). Imprecise continuous-time Markov chains. International Journal of Approximate Reasoning 88, 452-528.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
rctmc(),
transition2Generator()
Examples
states <- c("n", "y")
Q <- matrix(c(-1, 1, 1, -1), nrow = 2, byrow = TRUE,
dimnames = list(states, states))
range <- matrix(c(1/52, 3/52, 1/2, 2), nrow = 2, byrow = TRUE)
ictmc <- new("ictmc", states = states, Q = Q, range = range,
name = "testictmc")
impreciseProbabilityatT(ictmc, i = 2, t = 0, s = 1, error = 1e-3)
Hyperparameters for Bayesian estimation of a Markov chain
Description
The Bayesian estimation of the package uses independent Dirichlet priors for the rows of the transition matrix. This function infers their hyperparameters either from a prior transition matrix, taken as the prior mean, and a scale for each row (its total hyperparameter), or from a data set, as the transition counts plus one.
Usage
inferHyperparam(transMatr = matrix(), scale = numeric(), data = character())
Arguments
transMatr |
A prior transition matrix, with the states as dimnames. |
scale |
A numeric vector with the scale (sum of the hyperparameters)
of each row of |
data |
A sequence of states (or a data set accepted by
|
Details
Either data, or transMatr and scale, must be given.
Value
A list with element scaledInference (from transMatr and
scale) or dataInference (from data), the matrix of
hyperparameters. Its rows and columns are sorted alphanumerically by
state name.
Author(s)
Sai Bhargav Yalamanchi, Giorgio Spedicato
References
Yalamanchi, S. B. and Spedicato, G. A. (2015). Bayesian inference of first order Markov chains. Vignette of the markovchain package.
See Also
markovchainFit() (method = "map"), which uses them.
Other Bayesian inference:
predictiveDistribution(),
priorDistribution()
Examples
data(rain, package = "markovchain")
inferHyperparam(data = rain$rain)
weatherStates <- c("sunny", "cloudy", "rain")
weatherMatrix <- matrix(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))
Check whether a continuous time Markov chain is irreducible
Description
A continuous time Markov chain is irreducible if every state can be reached from every other state, which is the case if and only if its embedded jump chain is irreducible.
Usage
is.CTMCirreducible(ctmc)
Arguments
ctmc |
A |
Value
TRUE if the chain is irreducible, FALSE otherwise.
Author(s)
Vandit Jain
References
Sigman, K. (2009). Continuous-time Markov chains. Lecture notes, Columbia University.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.TimeReversible(),
probabilityatT(),
rctmc(),
transition2Generator()
Examples
energyStates <- c("sigma", "sigma_star")
gen <- matrix(c(-3, 3, 1, -1), nrow = 2, byrow = TRUE,
dimnames = list(energyStates, energyStates))
molecularCTMC <- new("ctmc", states = energyStates, byrow = TRUE,
generator = gen, name = "Molecular Transition Model")
is.CTMCirreducible(molecularCTMC)
Check whether a continuous time Markov chain is time reversible
Description
A continuous time Markov chain with stationary distribution
\pi is time reversible if it satisfies the detailed balance
equations \pi_i Q_{ij} = \pi_j Q_{ji} for all states i, j.
Usage
is.TimeReversible(ctmc)
Arguments
ctmc |
A |
Details
The equations are checked up to a relative tolerance of
\sqrt{\epsilon} (about 1.5 \times 10^{-8}) of the largest
flow \pi_i |Q_{ij}|, because \pi is computed numerically.
When the chain has several stationary distributions they must all
satisfy them.
Value
TRUE if the chain is time reversible, FALSE otherwise.
Author(s)
Vandit Jain
References
Dobrow, R. P. (2016). Introduction to Stochastic Processes with R. Wiley.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
probabilityatT(),
rctmc(),
transition2Generator()
Examples
energyStates <- c("sigma", "sigma_star")
gen <- matrix(c(-3, 3, 1, -1), nrow = 2, byrow = TRUE,
dimnames = list(energyStates, energyStates))
molecularCTMC <- new("ctmc", states = energyStates, byrow = TRUE,
generator = gen, name = "Molecular Transition Model")
is.TimeReversible(molecularCTMC)
# a birth-death chain is reversible, a cycle is not
s <- c("a", "b", "c")
birthDeath <- matrix(c(-0.3, 0.3, 0,
0.1, -0.5, 0.4,
0, 0.7, -0.7), nrow = 3, byrow = TRUE,
dimnames = list(s, s))
is.TimeReversible(new("ctmc", states = s, byrow = TRUE, generator = birthDeath))
cycle <- matrix(c(-1, 1, 0, 0, -1, 1, 1, 0, -1), nrow = 3, byrow = TRUE,
dimnames = list(s, s))
is.TimeReversible(new("ctmc", states = s, byrow = TRUE, generator = cycle))
Check whether a state can be reached from another
Description
Checks whether state to is accessible from state from,
i.e. whether the chain started in from reaches to with positive
probability in some number of steps.
Usage
is.accessible(object, from, to)
Arguments
object |
A |
from |
Name of the starting state. |
to |
Name of the target state. |
Value
TRUE if to is accessible from from, FALSE otherwise.
Author(s)
Giorgio Spedicato, Ignacio Cordón
References
James Montgomery, University of Madison
See Also
is.irreducible(), communicatingClasses()
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.2, 0.5, 0.3,
0, 1, 0,
0.1, 0.8, 0.1), nrow = 3, byrow = TRUE,
dimnames = list(statesNames, statesNames)
)
)
is.accessible(markovB, "a", "c")
Check whether a Markov chain is irreducible
Description
A Markov chain is irreducible if all its states communicate, i.e. form a single communicating class.
Usage
is.irreducible(object)
Arguments
object |
A |
Details
Irreducibility does not imply aperiodicity: an irreducible chain
on finitely many states has a unique stationary distribution, but it
converges to it from every initial state only if it is also aperiodic
(see period() and is.regular()).
Value
TRUE if the chain is irreducible, FALSE otherwise.
Author(s)
Giorgio Spedicato
References
Feres, Matlab listings for Markov Chains.
See Also
communicatingClasses(), is.regular(), period()
Examples
statesNames <- c("a", "b")
mcA <- new("markovchain", transitionMatrix = matrix(c(0.7,0.3,0.1,0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)
))
is.irreducible(mcA)
Check exact lumpability of a Markov chain
Description
Checks whether a Markov chain is (strongly) lumpable with
respect to a partition of its states: for every pair of blocks
A, B of the partition, all the states of A have the same
probability of moving into B (Kemeny and Snell 1960, Theorem
6.3.2). The aggregated process is then a Markov chain, for every initial
distribution.
Usage
is.lumpable(object, partition, tol = 1e-10)
## S4 method for signature 'markovchain'
is.lumpable(object, partition, tol = 1e-10)
Arguments
object |
A |
partition |
A named list of character vectors, the blocks of the partition (macro-states); every state must belong to exactly one block. |
tol |
Non-negative tolerance for the equality of the probabilities
(default |
Value
TRUE if the chain is lumpable with respect to partition,
FALSE otherwise.
References
Kemeny, J. G. and Snell, J. L. (1960). Finite Markov Chains. Van Nostrand.
See Also
Other state aggregation:
autoLump(),
lump()
Examples
statesNames <- c("a", "b", "c", "d")
P <- matrix(c(0.1, 0.2, 0.3, 0.4,
0.2, 0.1, 0.4, 0.3,
0.3, 0.3, 0.2, 0.2,
0.2, 0.4, 0.1, 0.3), nrow = 4, byrow = TRUE,
dimnames = list(statesNames, statesNames))
mc <- new("markovchain", states = statesNames, transitionMatrix = P)
partition <- list(ab = c("a", "b"), cd = c("c", "d"))
is.lumpable(mc, partition) # rows of a and b give 0.3/0.7 to ab/cd
is.lumpable(mc, list(ac = c("a", "c"), bd = c("b", "d")))
Check if a DTMC is regular
Description
Function to check wether a DTCM is regular
Usage
is.regular(object)
Arguments
object |
a markovchain object |
Details
A Markov chain is regular if some of the powers of its matrix has all elements
strictly positive. A finite chain is regular if and only if it is
irreducible and aperiodic (Horn and Johnson, Theorem 8.5.3 and Corollary
8.5.8), and this is how it is checked, from the communicating classes
and the period (period()); the work is O(n^2) for a dense
n-state chain.
Value
A boolean value
Author(s)
Ignacio Cordón
References
Matrix Analysis. Roger A.Horn, Charles R.Johnson. 2nd edition. Theorem 8.5.3, Corollary 8.5.8, Theorem 8.5.9
See Also
Examples
P <- matrix(c(0.5, 0.25, 0.25,
0.5, 0, 0.5,
0.25, 0.25, 0.5), nrow = 3)
colnames(P) <- rownames(P) <- c("R","N","S")
ciao <- as(P, "markovchain")
is.regular(ciao)
Check whether a Markov chain is reversible
Description
Checks whether a finite, irreducible discrete-time Markov chain is reversible with respect to its (unique) stationary distribution, i.e. whether it satisfies the detailed balance equations.
Usage
is.reversible(object, tolerance = sqrt(.Machine$double.eps))
## S4 method for signature 'markovchain'
is.reversible(object, tolerance = sqrt(.Machine$double.eps))
Arguments
object |
A |
tolerance |
A single finite non-negative number. Detailed balance is
accepted as holding when every pair |
Details
A chain with transition matrix P and stationary distribution
\pi is reversible if
\pi_i P_{ij} = \pi_j P_{ji} \quad \text{for every } i,j.
Intuitively, if you started the chain from \pi and watched a long
run of it, running the recorded sequence of states backwards would look
statistically identical to running it forwards: at stationarity, the
"flow" of probability from i to j exactly balances the flow
from j to i.
Only irreducibility is required, not aperiodicity: detailed balance is a
purely algebraic condition on P and \pi and is perfectly well
defined for periodic chains too. For example, a simple random walk on
any undirected graph (moving to a uniformly random neighbour) is always
reversible, whether or not it happens to be periodic.
A 2-state irreducible chain is always reversible: with only two states,
the single detailed balance equation \pi_1 P_{12} = \pi_2 P_{21} is
just a restatement of the stationarity equation \pi P = \pi, so it
holds automatically.
Every reversible chain has a real spectrum (all eigenvalues of P
are real), which is why slem and spectralGap
are especially easy to interpret for reversible chains: there are no
complex-conjugate eigenvalue pairs to reason about.
The implementation calls steadyStates once, then compares
the two triangles of the flow matrix \pi_i P_{ij}. Its time
complexity is dominated by steadyStates(), plus an additional
O(n^2) comparison for a dense n-state transition matrix. It
supports both row- and column-stochastic storage.
Value
A single logical value, TRUE or FALSE.
References
Norris, J. R. (1998). Markov Chains. Cambridge University Press.
Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times, 2nd edition. American Mathematical Society.
See Also
steadyStates, is.irreducible,
slem, mixingTime
Examples
# A random walk on a triangle is reversible.
statesNames <- c("a", "b", "c")
triangle <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0, 0.5, 0.5,
0.5, 0, 0.5,
0.5, 0.5, 0), byrow = TRUE, nrow = 3,
dimnames = list(statesNames, statesNames)))
is.reversible(triangle)
# A directed cycle (states only move "forward") is not reversible: there
# is a net clockwise flow of probability at stationarity.
cycle3 <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0, 1, 0,
0, 0, 1,
1, 0, 0), byrow = TRUE, nrow = 3,
dimnames = list(statesNames, statesNames)))
is.reversible(cycle3)
Check whether a Markov chain is stochastically monotone
Description
A Markov chain on ordered states is stochastically monotone
if starting from a higher state never makes the next state
stochastically smaller: for every pair of consecutive states i,
i + 1 and every j, \sum_{l \le j} P_{i+1, l} \le
\sum_{l \le j} P_{i, l}.
Usage
is.stochasticallyMonotone(object)
## S4 method for signature 'markovchain'
is.stochasticallyMonotone(object)
## S4 method for signature 'matrix'
is.stochasticallyMonotone(object)
## S4 method for signature 'ANY'
is.stochasticallyMonotone(object)
Arguments
object |
A |
Details
The states are taken in the order of the transition matrix, and
the inequalities are checked up to a tolerance of 10^{-10}.
Value
TRUE if the chain is stochastically monotone, FALSE otherwise.
References
Keilson, J. and Kester, A. (1977). Monotone matrices and monotone Markov processes. Stochastic Processes and their Applications 5(3), 231-241.
Examples
# a birth-death chain is monotone
P <- matrix(c(0.7, 0.3, 0,
0.2, 0.5, 0.3,
0, 0.4, 0.6), nrow = 3, byrow = TRUE,
dimnames = list(c("low", "mid", "high"), c("low", "mid", "high")))
is.stochasticallyMonotone(new("markovchain", transitionMatrix = P))
# reversing the order of the rows breaks monotonicity
is.stochasticallyMonotone(P[3:1, ])
Kemeny's constant of a Markov chain
Description
Computes Kemeny's constant for a finite, irreducible discrete-time Markov chain. It is the stationary-distribution-weighted mean hitting time of a randomly selected destination and is independent of the starting state.
Usage
kemenyConstant(object)
## S4 method for signature 'markovchain'
kemenyConstant(object)
Arguments
object |
A |
Details
For a row-stochastic transition matrix P, let \pi be its unique
stationary distribution and define
Z = (I - P + \mathbf{1}\pi^T)^{-1}.
With hitting times defined by
T_j = \inf\{n \ge 0: X_n=j\}, so that m_{jj}=0, the function
returns
K = \sum_j \pi_j m_{ij} = \mathrm{tr}(Z)-1.
The value does not depend on the starting state i.
Irreducibility is sufficient; aperiodicity is not required. Reducible chains can have multiple stationary distributions and are rejected.
Some references instead put the mean first-return time
m_{jj}=1/\pi_j on the diagonal. Under that convention the corresponding
stationary weighted sum is K+1, not K. This function uses the
zero-diagonal hitting-time convention, consistently with
meanFirstPassageTime().
The implementation uses a dense LAPACK solve for the fundamental matrix
Z. Its time complexity is O(n^3) and its memory use is
O(n^2), as expected for a dense exact computation. It supports both
row- and column-stochastic storage.
Value
A numeric scalar containing Kemeny's constant.
References
Kemeny, J. G. and Snell, J. L. (1960). Finite Markov Chains. D. Van Nostrand, Princeton, NJ.
See Also
meanFirstPassageTime,
steadyStates, is.irreducible
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
kemenyConstant(mc)
Example from Kullback and Kupperman Tests for Contingency Tables
Description
A list of two matrices representing raw transitions between two states
Usage
data(kullback)
Format
A list containing two 6x6 non - negative integer matrices
Build a lazy version of a Markov chain
Description
Constructs the "lazy" chain associated with a markovchain object:
at every step, stay put with probability alpha and otherwise take
a step of the original chain.
Usage
lazyChain(object, alpha = 0.5)
## S4 method for signature 'markovchain'
lazyChain(object, alpha = 0.5)
Arguments
object |
A |
alpha |
A single number in |
Details
For a transition matrix P (in whichever storage convention
object already uses) and a laziness parameter
\alpha\in[0,1], the lazy chain's transition matrix is
L = \alpha I + (1-\alpha) P.
Laziness is a standard device for forcing aperiodicity without changing where the chain can go or its stationary distribution:
-
Lhas the same stationary distribution asP(if\pi P=\pithen\pi L = \alpha\pi + (1-\alpha)\pi P = \pi), and the same communicating classes, sinceL_{ij}>0 \iff P_{ij}>0fori\ne j. For
0<\alpha<1,Lis aperiodic even ifPis periodic, becauseL_{ii}=\alpha>0for every stateirules out any period greater than1. This is whymixingTime, which requires aperiodicity, is often applied tolazyChain(object)rather than to a periodicobjectdirectly (seemixingTime's own documentation for why it rejects periodic chains outright rather than lazifying them automatically).Every non-trivial eigenvalue of
Lis\alpha + (1-\alpha)\lambdafor the corresponding eigenvalue\lambdaofP: laziness shrinks the whole non-trivial spectrum towards\alpha, soslemandimpliedTimescalesgenerally get worse (mixing gets slower) asalphaincreases towards1.
\alpha=0 returns P unchanged; \alpha=1 returns the
identity matrix (a chain that never moves).
Value
A new markovchain object with transition matrix
L = \alpha I + (1-\alpha) P, the same states, and the same
row/column-stochastic storage convention (byrow) as
object.
References
Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times, 2nd edition. American Mathematical Society.
See Also
Examples
# A 2-cycle is periodic (period 2); its lazy version is aperiodic.
statesNames <- c("a", "b")
cycle2 <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0, 1, 1, 0), byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
period(cycle2)
lazyCycle2 <- lazyChain(cycle2, alpha = 0.5)
period(lazyCycle2)
steadyStates(cycle2)
steadyStates(lazyCycle2) # unchanged by laziness
Aggregate a Markov chain over a partition
Description
Builds the chain on the blocks (macro-states) of a partition
of the states. By default the chain must be exactly lumpable with respect
to the partition (see is.lumpable()); with force = TRUE an
approximate aggregation is returned for any partition.
Usage
lump(object, partition, force = FALSE)
## S4 method for signature 'markovchain'
lump(object, partition, force = FALSE)
Arguments
object |
A |
partition |
A named list of character vectors, the blocks of the partition; the names become the states of the result. |
force |
Logical: if |
Details
The probability of moving from block A to block B is
the average over the states of A of their probability of moving
into B, weighted by the stationary distribution (the average of the
stationary distributions if there are several; equal weights within a
block with zero stationary mass). For a lumpable chain all the states of
a block give the same value, so the weights do not matter; otherwise the
result is the usual stationary-weighted approximation, which preserves
the stationary distribution of the blocks.
Value
A row-stochastic markovchain object on the
blocks.
References
Kemeny, J. G. and Snell, J. L. (1960). Finite Markov Chains. Van Nostrand.
See Also
Other state aggregation:
autoLump(),
is.lumpable()
Examples
statesNames <- c("a", "b", "c", "d")
P <- matrix(c(0.1, 0.2, 0.3, 0.4,
0.2, 0.1, 0.4, 0.3,
0.3, 0.3, 0.2, 0.2,
0.2, 0.4, 0.1, 0.3), nrow = 4, byrow = TRUE,
dimnames = list(statesNames, statesNames))
mc <- new("markovchain", states = statesNames, transitionMatrix = P)
partition <- list(ab = c("a", "b"), cd = c("c", "d"))
lump(mc, partition)
# an approximate aggregation over a partition that is not lumpable
lump(mc, list(ac = c("a", "c"), bd = c("b", "d")), force = TRUE)
Markov Chain class
Description
The S4 class that describes markovchain objects.
Slots
statesName of the states. Must be the same of
colnamesandrownamesof the transition matrixbyrowTRUE or FALSE indicating whether the supplied matrix is either stochastic by rows or by columns
transitionMatrixSquare transition matrix
nameOptional character name of the Markov chain
Creation of objects
Objects can be created by calls of the form new("markovchain", states, byrow, transitionMatrix, ...).
Methods
*signature(e1 = "markovchain", e2 = "markovchain"): multiply twomarkovchainobjects*signature(e1 = "markovchain", e2 = "matrix"): markovchain by matrix multiplication*signature(e1 = "markovchain", e2 = "numeric"): markovchain by numeric vector multiplication*signature(e1 = "matrix", e2 = "markovchain"): matrix by markov chain*signature(e1 = "numeric", e2 = "markovchain"): numeric vector bymarkovchainmultiplication[signature(x = "markovchain", i = "ANY", j = "ANY", drop = "ANY"): ...^signature(e1 = "markovchain", e2 = "numeric"): power of amarkovchainobject- ==
signature(e1 = "markovchain", e2 = "markovchain"): equality of twomarkovchainobject- !=
signature(e1 = "markovchain", e2 = "markovchain"): non-equality of twomarkovchainobject- absorbingStates
signature(object = "markovchain"): method to get absorbing states- canonicForm
signature(object = "markovchain"): return amarkovchainobject into canonic form- coerce
signature(from = "markovchain", to = "data.frame"): coerce method from markovchain todata.frame- conditionalDistribution
signature(object = "markovchain"): returns the conditional probability of subsequent states given a state- coerce
signature(from = "data.frame", to = "markovchain"): coerce method fromdata.frametomarkovchain- coerce
signature(from = "table", to = "markovchain"): coerce method fromtabletomarkovchain- coerce
signature(from = "msm", to = "markovchain"): coerce method frommsmtomarkovchain- coerce
signature(from = "msm.est", to = "markovchain"): coerce method frommsm.est(but only from a Probability Matrix) tomarkovchain- coerce
signature(from = "etm", to = "markovchain"): coerce method frometmtomarkovchain- coerce
signature(from = "sparseMatrix", to = "markovchain"): coerce method fromsparseMatrixtomarkovchain- coerce
signature(from = "markovchain", to = "igraph"): coercing toigraphobjects- coerce
signature(from = "markovchain", to = "matrix"): coercing tomatrixobjects- coerce
signature(from = "markovchain", to = "sparseMatrix"): coercing tosparseMatrixobjects- coerce
signature(from = "matrix", to = "markovchain"): coercing tomarkovchainobjects frommatrixone- dim
signature(x = "markovchain"): method to get the size- names
signature(x = "markovchain"): method to get the names of states- names<-
signature(x = "markovchain", value = "character"): method to set the names of states- initialize
signature(.Object = "markovchain"): initialize method- plot
signature(x = "markovchain", y = "missing"): plot method formarkovchainobjects- predict
signature(object = "markovchain"): predict method. Starting from the last element ofnewdata, which must be a state of the chain, it returns then.aheadfollowing states, each being the most probable transition from the previous one; ties are broken at random.signature(x = "markovchain"): print method.- show
signature(object = "markovchain"): show method.- sort
signature(x = "markovchain", decreasing=FALSE): sorting the transition matrix.- states
signature(object = "markovchain"): returns the names of states (asnames.- steadyStates
signature(object = "markovchain"): method to get the steady vector.- summary
signature(object = "markovchain"): method to summarize structure of the markov chain.summary(object, details = TRUE)also prints, after the usual output, the size and rank of the transition matrix, the number of communicating classes, irreducibility, period, regularity, whether the chain is absorbing, reversible, stochastically monotone and symmetric, and, when they are defined, the entropy rate, the SLEM, the spectral gap and Kemeny's constant; these values are also returned, invisibly, in thedetailselement of the result.- transientStates
signature(object = "markovchain"): method to get the transient states.- t
signature(x = "markovchain"): transpose matrix- transitionProbability
signature(object = "markovchain"): transition probability
Note
-
markovchainobject are backed by S4 Classes. Validation method is used to assess whether either columns or rows totals to one. Rounding is used up to
.Machine$double.eps * 100. If state names are not properly defined for a probabilitymatrix, coercing tomarkovchainobject leads to overriding states name with artificial "s1", "s2", ... sequence. In addition, operator overloading has been applied for+,*,^,==,!=operators.
Author(s)
Giorgio Spedicato
References
A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
See Also
markovchainSequence,markovchainFit
Examples
#show markovchain definition
showClass("markovchain")
#create a simple Markov chain
transMatr<-matrix(c(0.4,0.6,.3,.7),nrow=2,byrow=TRUE)
simpleMc<-new("markovchain", states=c("a","b"),
transitionMatrix=transMatr,
name="simpleMc")
#power
simpleMc^4
#some methods
steadyStates(simpleMc)
absorbingStates(simpleMc)
simpleMc[2,1]
t(simpleMc)
is.irreducible(simpleMc)
#conditional distributions
conditionalDistribution(simpleMc, "b")
#example for predict method
sequence<-c("a", "b", "a", "a", "a", "a", "b", "a", "b", "a", "b", "a", "a", "b", "b", "b", "a")
mcFit<-markovchainFit(data=sequence)
predict(mcFit$estimate, newdata="b",n.ahead=3)
#direct conversion
myMc<-as(transMatr, "markovchain")
#example of summary
summary(simpleMc)
summary(simpleMc, details = TRUE)
## Not run: plot(simpleMc)
Session cache of eigenvalues
Description
Functions of the package that need the eigenvalues of a transition matrix
(slem, spectralGap,
relaxationTime, impliedTimescales,
topologicalEntropy, aggregateStates with
k = NULL, autoplot(type = "eigenvalues") and
summary(details = TRUE)) compute them once per matrix and keep them
for the rest of the R session, so that calling several of these functions
on the same chain does not repeat the O(n^3) eigen-decomposition.
Details
A stored result is reused only for a matrix bitwise identical to the one it was computed from (state names are ignored), so results are exactly the same with or without the cache. The most recently used matrices are kept within a memory budget.
Options
markovchain.cacheLogical;
FALSEswitches the cache off. DefaultTRUE.markovchain.cacheSizeMemory budget of the cache in bytes, default
64 * 1024^2(64 MiB). A matrix larger than the budget is not stored.
Examples
mc <- new("markovchain", states = c("a", "b", "c"),
transitionMatrix = matrix(c(0.5, 0.3, 0.2,
0.1, 0.8, 0.1,
0.3, 0.3, 0.4), nrow = 3, byrow = TRUE))
slem(mc) # computes the eigenvalues
spectralGap(mc) # reuses them
# switch the cache off for the rest of the session
old <- options(markovchain.cache = FALSE)
spectralGap(mc)
options(old)
Fit a discrete time Markov chain
Description
Estimates the transition matrix of a homogeneous discrete
time Markov chain from observed sequences of states, by maximum
likelihood (optionally with Laplace smoothing), by bootstrap, or by
maximum a posteriori (Bayesian) estimation with Dirichlet priors.
createSequenceMatrix() returns the matrix of transition counts (or
frequencies) on which the estimates are based.
Usage
.markovchainFitRcpp(
data,
method = "mle",
byrow = TRUE,
nboot = 10L,
laplacian = 0,
name = "",
parallel = FALSE,
confidencelevel = 0.95,
confint = TRUE,
hyperparam = matrix(),
sanitize = FALSE,
possibleStates = character(),
progress = FALSE
)
createSequenceMatrix(
stringchar,
toRowProbs = FALSE,
sanitize = FALSE,
possibleStates = character()
)
markovchainFit(data, method = "mle", byrow = TRUE, nboot = 10L,
laplacian = 0, name = "", parallel = FALSE, confidencelevel = 0.95,
confint = TRUE, hyperparam = matrix(), sanitize = FALSE,
possibleStates = character(), absorbingStates = character(),
progress = FALSE, num.cores = NULL)
Arguments
data |
The observed sequence(s): a character vector (one sequence), a
list of character vectors (independent sequences), or a matrix or data
frame with one trajectory per row (per column if |
method |
Method used to estimate the Markov chain. Either "mle", "map", "bootstrap" or "laplace". All four are available for a single sequence. For a list of sequences, "mle", "map" and "laplace" pool the transition counts over the sequences, while "bootstrap" is not available and raises an error explaining why. |
byrow |
For a character vector or a list of sequences, it tells whether the fitted
transition matrix is stored by row (the default) or by column; the
|
nboot |
Number of bootstrap replicates in case "bootstrap" is used. |
laplacian |
Laplacian smoothing parameter, default zero. It is only used when "laplace" method is chosen. |
name |
Optional character for name slot. |
parallel |
Use parallel processing when performing Boostrap estimates. |
confidencelevel |
Confidence level of the intervals (default 0.95). |
confint |
Logical: compute standard errors and confidence intervals
(default |
hyperparam |
For |
sanitize |
how to deal with the states that have no observed outgoing
transition, which is what |
possibleStates |
States to include in the result even if they do not appear in the data. |
progress |
Should a text progress bar be shown? It is only used by the "bootstrap" method, the other methods being fast; see Details. |
stringchar |
For |
toRowProbs |
Logical: return the transition frequencies (each row divided by its total) instead of the counts? |
absorbingStates |
Character vector of states that are known a priori to be
absorbing. The corresponding rows are set to the identity row after MLE
fitting when |
num.cores |
Number of threads the parallel bootstrap path uses when
|
Details
Disabling confint would lower the computation time on large datasets. If data or stringchar
contain NAs, the related NA containing transitions will be ignored.
With progress = TRUE the "bootstrap" method shows a text progress bar
(txtProgressBar, style 3) covering the simulation of the
nboot bootstrap sequences and the estimation of a transition matrix
from each of them. With parallel = TRUE the sequences are simulated in
parallel threads, which cannot report progress, so the bar only covers the
estimation step. The computation can be interrupted while the bar is shown.
When absorbingStates is supplied, the declared states must have
no observed outgoing transitions. This allows terminal states in censored
customer journeys to be represented as absorbing states without adding
artificial observations.
sanitize = "absorbing" reaches the same result without
naming the states: every state that has no observed outgoing transition,
which is what possibleStates typically introduces, is made
absorbing. Unlike absorbingStates, it works with every
method, since it only replaces the uniform row that
sanitize = TRUE would have produced. As with
absorbingStates, only the estimate is constrained: any confidence
bounds and standard errors keep the values the unconstrained fit assigned
to those rows.
Value
markovchainFit() returns a list whose element estimate is the
fitted markovchain object. The other elements
depend on the method:
-
"mle":standardError,confidenceLevel,lowerEndpointMatrix,upperEndpointMatrix(whenconfint = TRUE) andlogLikelihood; -
"laplace":logLikelihood; -
"map":expectedValue(posterior mean of the transition matrix),standardError,confidenceIntervalandlogLikelihood; -
"bootstrap":standardError,confidenceInterval,bootStrapSamplesandlogLikelihood.
For matrix or data frame input only the maximum likelihood estimate is
computed, whatever method, and there is no logLikelihood.
createSequenceMatrix() returns the square matrix of transition counts
(frequencies, with toRowProbs = TRUE), with the states as dimnames.
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 data is either a data.frame or a matrix object, only MLE fit is
currently available.
Author(s)
Giorgio Spedicato, Tae Seung Kang, Sai Bhargav Yalamanchi
References
Anderson, T. W. and Goodman, L. A. (1957). Statistical inference about Markov chains. The Annals of Mathematical Statistics 28(1), 89-110.
Strelioff, C. C., Crutchfield, J. P. and Hubler, A. W. (2007). Inferring Markov chains: Bayesian estimation, model comparison, entropy rate, and out-of-class modeling. Physical Review E 76, 011106. doi:10.1103/PhysRevE.76.011106
Yalamanchi, S. B. and Spedicato, G. A. (2015). Bayesian inference of first order Markov chains. Vignette of the markovchain package.
See Also
markovchainSequence, 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")
Non-homogeneous discrete time Markov chain class
Description
The S4 class of non-homogeneous discrete time Markov chains:
a sequence of markovchain objects, the k-th
giving the transition probabilities from time k - 1 to time
k.
Slots
markovchainsA list of
markovchainobjects.nameOptional name of the object.
Objects from the Class
Objects are created with new("markovchainList", markovchains = list(...))
or estimated by markovchainListFit(). The transition probabilities, and
the states, may change from one time to the next.
Methods
- [[
signature(x = "markovchainList"): extract the i-thmarkovchain- dim
signature(x = "markovchainList"): number ofmarkovchainunderlying the matrix- predict
signature(object = "markovchainList"): predict from amarkovchainListsignature(x = "markovchainList"): prints the list of markovchains- show
signature(object = "markovchainList"): same asprint
Note
The class consists in a list of markovchain objects.
It is aimed at working with non homogeneous Markov chains.
Author(s)
Giorgio Spedicato
References
A First Course in Probability (8th Edition), Sheldon Ross, Prentice Hall 2010
See Also
Examples
showClass("markovchainList")
#define a markovchainList
statesNames=c("a","b")
mcA<-new("markovchain",name="MCA",
transitionMatrix=matrix(c(0.7,0.3,0.1,0.9),
byrow=TRUE, nrow=2,
dimnames=list(statesNames,statesNames))
)
mcB<-new("markovchain", states=c("a","b","c"), name="MCB",
transitionMatrix=matrix(c(0.2,0.5,0.3,0,1,0,0.1,0.8,0.1),
nrow=3, byrow=TRUE))
mcC<-new("markovchain", states=c("a","b","c","d"), name="MCC",
transitionMatrix=matrix(c(0.25,0.75,0,0,0.4,0.6,
0,0,0,0,0.1,0.9,0,0,0.7,0.3),
nrow=4, byrow=TRUE)
)
mcList<-new("markovchainList",markovchains=list(mcA, mcB, mcC),
name="Non - homogeneous Markov Chain")
Fit a non-homogeneous Markov chain
Description
Estimates a non-homogeneous discrete time Markov chain, with one transition matrix for each pair of consecutive times, from a panel of trajectories observed at the same times.
Usage
markovchainListFit(data, byrow = TRUE, laplacian = 0, name)
Arguments
data |
The trajectories: a matrix or data frame with one trajectory
per row and one time per column (or the transpose, see |
byrow |
Logical: for a matrix or data frame, is each trajectory a row (default) or a column? |
laplacian |
Laplace smoothing: a constant added to every transition count before normalizing (default 0). |
name |
Optional name of the fitted
|
Details
The k-th transition matrix is the maximum likelihood
estimate from the transitions observed between times k and
k + 1 (columns k and k + 1, or positions k and
k + 1 of the trajectories long enough). Transitions with a missing
value (NA) are ignored, and pairs of times without any complete
transition are skipped.
Value
A list with element estimate, the fitted
markovchainList; an empty list if no
transition can be counted.
See Also
markovchainFit() for a homogeneous chain, rmarkovchain() to
simulate from the fit.
Examples
data(holson)
# a homogeneous chain for the whole panel
singleMc <- markovchainFit(data = holson[, 2:12])
# one transition matrix for each pair of consecutive years
mclistFit <- markovchainListFit(data = holson[, 2:12], name = "holsonMcList")
mclistFit$estimate
Simulate a trajectory of a Markov chain
Description
Simulates n steps of a homogeneous discrete time Markov
chain from the initial state t0, drawing each state from the
transition probabilities of the previous one.
Usage
markovchainSequence(
n,
markovchain,
t0 = sample(markovchain@states, 1),
include.t0 = FALSE,
useRCpp = TRUE
)
Arguments
n |
Number of steps, a non-negative integer. |
markovchain |
A |
t0 |
Name of the initial state. The default draws it uniformly at random among the states. |
include.t0 |
Logical: include the initial state in the output? If
|
useRCpp |
Logical: use the C++ implementation (default) or the R one? Both give the same sequence for the same random seed. |
Value
A character vector with the simulated states.
Author(s)
Giorgio Spedicato
References
Ross, S. (2010). A First Course in Probability (8th edition). Prentice Hall.
See Also
rmarkovchain(), which also simulates from non-homogeneous chains
(markovchainList objects);
markovchainFit() for the reverse operation.
Other simulation:
rmarkovchain()
Examples
statesNames <- c("a", "b", "c")
mcB <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1),
nrow = 3, byrow = TRUE, dimnames = list(statesNames, statesNames)))
markovchainSequence(n = 20, markovchain = mcB, t0 = "a")
markovchainSequence(n = 20, markovchain = mcB, t0 = "a", include.t0 = TRUE)
Mean absorption time
Description
Computes the expected number of steps to go from any of the transient states to any of the recurrent states. The Markov chain should have at least one transient state for this method to work
Usage
meanAbsorptionTime(object)
Arguments
object |
the markovchain object |
Value
A named vector with the expected number of steps to go from a transient state to any of the recurrent ones
Author(s)
Ignacio Cordón
References
C. M. Grinstead and J. L. Snell. Introduction to Probability. American Mathematical Soc., 2012.
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
m <- matrix(c(1/2, 1/2, 0,
1/2, 1/2, 0,
0, 1/2, 1/2), ncol = 3, byrow = TRUE)
mc <- new("markovchain", states = letters[1:3], transitionMatrix = m)
times <- meanAbsorptionTime(mc)
Mean first passage times of an irreducible Markov chain
Description
Given an irreducible (ergodic) markovchain object, this function calculates the expected number of steps to reach other states
Usage
meanFirstPassageTime(object, destination)
Arguments
object |
the markovchain object |
destination |
a character vector representing the states respect to which we want to compute the mean first passage time. Empty by default |
Details
For an ergodic Markov chain it computes:
If destination is empty, the average first time (in steps) that takes the Markov chain to go from initial state i to j. (i, j) represents that value in case the Markov chain is given row-wise, (j, i) in case it is given col-wise.
If destination is not empty, the average time it takes us from the remaining states to reach the states in
destination
Value
a Matrix of the same size with the average first passage times if destination is empty, a vector if destination is not
Author(s)
Toni Giorgino, Ignacio Cordón
References
C. M. Grinstead and J. L. Snell. Introduction to Probability. American Mathematical Soc., 2012.
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanNumVisits(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
m <- matrix(1 / 10 * c(6,3,1,
2,3,5,
4,1,5), ncol = 3, byrow = TRUE)
mc <- new("markovchain", states = c("s","c","r"), transitionMatrix = m)
meanFirstPassageTime(mc, "r")
# Grinstead and Snell's "Oz weather" worked out example
mOz <- matrix(c(2,1,1,
2,0,2,
1,1,2)/4, ncol = 3, byrow = TRUE)
mcOz <- new("markovchain", states = c("s", "c", "r"), transitionMatrix = mOz)
meanFirstPassageTime(mcOz)
Mean number of visits to each state
Description
Given a markovchain object, this function calculates a matrix where the element (i, j) represents the expect number of visits to the state j if the chain starts at i (in a Markov chain by columns it would be the element (j, i) instead)
Usage
meanNumVisits(object)
Arguments
object |
the markovchain-class object |
Value
a matrix with the expect number of visits to each state
Author(s)
Ignacio Cordón
References
R. Vélez, T. Prieto, Procesos Estocásticos, Librería UNED, 2013
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanRecurrenceTime(),
noofVisitsDist()
Examples
M <- markovchain:::zeros(5)
M[1,1] <- M[5,5] <- 1
M[2,1] <- M[2,3] <- 1/2
M[3,2] <- M[3,4] <- 1/2
M[4,2] <- M[4,5] <- 1/2
mc <- new("markovchain", transitionMatrix = M)
meanNumVisits(mc)
Mean recurrence time
Description
Computes the expected time to return to a recurrent state in case the Markov chain starts there
Usage
meanRecurrenceTime(object)
Arguments
object |
the markovchain object |
Value
For a Markov chain it outputs is a named vector with the expected time to first return to a state when the chain starts there. States present in the vector are only the recurrent ones. If the matrix is ergodic (i.e. irreducible), then all states are present in the output and order is the same as states order for the Markov chain
Author(s)
Ignacio Cordón
References
C. M. Grinstead and J. L. Snell. Introduction to Probability. American Mathematical Soc., 2012.
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
noofVisitsDist()
Examples
m <- matrix(1 / 10 * c(6,3,1,
2,3,5,
4,1,5), ncol = 3, byrow = TRUE)
mc <- new("markovchain", states = c("s","c","r"), transitionMatrix = m)
meanRecurrenceTime(mc)
Merge two Markov chains by convex combination of their transition matrices
Description
Builds a new markovchain object whose transition matrix is a convex
combination of the transition matrices of two existing chains defined on
the same state space.
Usage
mergeWith(object, other, gamma = 0.5)
## S4 method for signature 'markovchain,markovchain'
mergeWith(object, other, gamma = 0.5)
Arguments
object |
A |
other |
A second |
gamma |
A single number in |
Details
For transition matrices P_1 (from object) and P_2
(from other), and a blending factor \gamma\in[0,1], the
merged transition matrix is
P = (1-\gamma) P_1 + \gamma P_2.
States are matched by name, not by position. object and
other must have exactly the same set of state names (as sets –
other's states may be in a different order, or other may use
a different storage convention (byrow), and both are handled
correctly). Rows and columns of other's transition matrix are
realigned to object's state order before combining, and both
matrices are converted to row-stochastic form first if needed, so that
P_1 and P_2 are always combined entry-for-entry between
matching states rather than between matching matrix positions.
This is a deliberate difference from the na\"ive version of this
operation, which combines two same-size transition matrices
positionally and would silently produce a meaningless result if the two
chains happened to list their states in a different order (or under a
different byrow convention) despite describing the same states.
Requiring identical state name sets, rather than merely identical size,
catches that mismatch as an error instead of propagating it.
Because P_1 and P_2 are both row-stochastic with non-negative
entries and \gamma\in[0,1], P is automatically row-stochastic
with non-negative entries: no renormalization is needed (this is the same
convexity argument used for lazyChain, of which
mergeWith(object, identity_chain, gamma) is a special case when
other is an identity chain on the same states).
This function does not require object or other to be
irreducible: merging is meaningful for any two chains on the same state
space, including reducible ones. Note, however, that the merged chain's
stationary distribution (if any) is generally not a combination of
\pi_1 and \pi_2 in any simple way; it must be recomputed from
P directly.
The implementation performs no eigendecomposition and is O(n^2)
time and memory for two n-state chains, dominated by realigning
other's matrix to object's state order.
Value
A new markovchain object, row-stochastic, on the common
state names, with transition matrix P = (1-\gamma)P_1+\gamma P_2.
See Also
Examples
statesNames <- c("a", "b")
mc1 <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.9, 0.1, 0.1, 0.9), byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
# mc2 lists the same two states in the opposite order.
mc2 <- new("markovchain", states = rev(statesNames),
transitionMatrix = matrix(c(0.5, 0.5, 0.5, 0.5), byrow = TRUE, nrow = 2,
dimnames = list(rev(statesNames), rev(statesNames))))
merged <- mergeWith(mc1, mc2, gamma = 0.5)
merged
# States are matched by name: merged["a", "b"] combines mc1["a","b"] with
# mc2["a","b"], not with whatever happened to sit in the same matrix cell.
Mixing time of a Markov chain
Description
Estimates the total-variation mixing time of a finite, irreducible,
aperiodic (i.e. ergodic) discrete-time Markov chain: the smallest number
of steps after which the chain's distribution is within epsilon of
its stationary distribution, from every possible starting state.
Usage
mixingTime(object, epsilon = 0.25, maxIter = 10000L)
## S4 method for signature 'markovchain'
mixingTime(object, epsilon = 0.25, maxIter = 10000L)
Arguments
object |
A |
epsilon |
A single number strictly between |
maxIter |
A single positive integer: the largest |
Details
For a row-stochastic transition matrix P with stationary
distribution \pi, define the worst-case total variation distance
after t steps as
d(t) = \max_i \tfrac{1}{2}\sum_j |P^t_{ij} - \pi_j|.
The mixing time returned is
t_{\mathrm{mix}}(\varepsilon) = \min\{t \ge 1 : d(t) \le \varepsilon\}.
Unlike slem, spectralGap and
impliedTimescales, mixingTime() requires
aperiodicity in addition to irreducibility. This is not an arbitrary
restriction carried over from another implementation: for a periodic
chain, P^t(i, \cdot) never converges to \pi at all (it keeps
cycling through a fixed set of distributions), so d(t) does not go
to zero and "the number of steps until d(t) \le \varepsilon" is
simply undefined for small enough \varepsilon. slem() and
spectralGap() remain meaningful for periodic chains because they
summarise the transition matrix's spectrum directly, without reference
to a limit that may not exist.
The implementation repeatedly forms P^{t+1} = P^t P and checks
d(t) after each multiplication, starting from t=1, until the
threshold is met or maxIter is reached. Its time complexity is
O(t_{\mathrm{mix}} \cdot n^3) and its memory use is O(n^2)
for a dense n-state transition matrix: this is a direct,
easy-to-audit computation, not an asymptotically optimal one (a
repeated-squaring scheme would reach a single large power of P
faster, but would not let every intermediate t be checked against
epsilon along the way). It supports both row- and
column-stochastic storage.
Value
A single positive integer, the estimated mixing time
t_{\mathrm{mix}}(\varepsilon). For the trivial one-state chain,
0 is returned (it is its own stationary distribution).
References
Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times, 2nd edition. American Mathematical Society.
See Also
slem, spectralGap,
impliedTimescales, period,
is.irreducible
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
mixingTime(mc)
mixingTime(mc, epsilon = 0.01) # a tighter threshold needs more steps
Simultaneous confidence intervals for transition probabilities
Description
Simultaneous confidence intervals for the rows of an estimated transition matrix, each row being a multinomial proportion, by the method of Sison and Glaz (1995) in the implementation of May and Johnson (2000).
Usage
multinomialConfidenceIntervals(
transitionMatrix,
countsTransitionMatrix,
confidencelevel = 0.95
)
Arguments
transitionMatrix |
The estimated transition matrix. |
countsTransitionMatrix |
The matrix of transition counts from which
|
confidencelevel |
Confidence level (default 0.95). |
Value
A list with confidenceLevel, lowerEndpointMatrix and
upperEndpointMatrix, the latter two with the dimnames of
transitionMatrix.
References
Sison, C. P. and Glaz, J. (1995). Simultaneous confidence intervals and sample size determination for multinomial proportions. Journal of the American Statistical Association 90, 366-369.
May, W. L. and Johnson, W. D. (2000). Constructing two-sided simultaneous confidence intervals for multinomial proportions for small counts in a large number of cells. Journal of Statistical Software 5(6).
See Also
markovchainFit(), whose method = "mle" gives intervals for
each probability separately rather than simultaneous ones for each row.
Examples
seq <- c("a", "b", "a", "a", "a", "a", "b", "a", "b", "a", "b", "a", "a",
"b", "b", "b", "a")
mcfit <- markovchainFit(data = seq, byrow = TRUE)
seqmat <- createSequenceMatrix(seq)
multinomialConfidenceIntervals(mcfit$estimate@transitionMatrix, seqmat, 0.95)
Name of a Markov chain
Description
Returns the name of a markovchain
object (its name slot).
Usage
name(object)
## S4 method for signature 'markovchain'
name(object)
Arguments
object |
A |
Value
A character string.
Author(s)
Giorgio Spedicato, Deepak Yadav
See Also
name<- to change it.
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames=list(statesNames,statesNames)),
name = "A markovchain Object"
)
name(markovB)
Set the name of a Markov chain
Description
Replaces the name of a markovchain
object (its name slot).
Usage
name(object) <- value
## S4 replacement method for signature 'markovchain'
name(object) <- value
Arguments
object |
A |
value |
The new name, a character string. |
Value
The object with the new name (used as name(object) <- value).
Author(s)
Giorgio Spedicato, Deepak Yadav
See Also
name() to read it.
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames=list(statesNames,statesNames)),
name = "A markovchain Object"
)
name(markovB) <- "dangerous mc"
name(markovB)
Returns the states for a Markov chain object
Description
Returns the states for a Markov chain object
Usage
## S4 method for signature 'markovchain'
names(x)
Arguments
x |
object we want to return states for |
Expected fraction of the first N steps spent in each state
Description
Given the initial state i, returns for every state
j the expected fraction of the first N steps that the DTMC
spends in j.
Usage
noofVisitsDist(markovchain,N,state)
Arguments
markovchain |
a markovchain-class object |
N |
number of steps, a positive integer |
state |
the initial state |
Details
The value for state j is
\frac{1}{N}\sum_{k=1}^{N} (P^k)_{ij} = \frac{E[V_j(N)]}{N},
where V_j(N) is the number of visits to j at times
1, \dots, N (the initial state, at time 0, is not counted). The
values sum to one, and multiplied by N they give the expected
numbers of visits. As N grows they converge to the stationary
distribution for an irreducible chain.
Despite the name of the function, and the title of earlier versions of this
page, the result is not the joint distribution of the numbers of visits
(V_1(N), \dots, V_n(N)), which the package does not compute (see
issue #139).
Value
a named numeric vector with one element per state, summing to one.
Author(s)
Vandit Jain
See Also
Other first passage and hitting:
absorptionProbabilities(),
committorAB(),
firstPassage(),
firstPassageMultiple(),
hittingProbabilities(),
meanAbsorptionTime(),
meanFirstPassageTime(),
meanNumVisits(),
meanRecurrenceTime()
Examples
transMatr<-matrix(c(0.4,0.6,.3,.7),nrow=2,byrow=TRUE)
simpleMc<-new("markovchain", states=c("a","b"),
transitionMatrix=transMatr,
name="simpleMc")
noofVisitsDist(simpleMc,5,"a")
# expected numbers of visits during the first 5 steps
5 * noofVisitsDist(simpleMc,5,"a")
Normalized entropy rate of a Markov chain
Description
The entropy rate of a finite irreducible Markov chain divided by the topological entropy of its graph, a measure of how random the chain is relative to the most random chain with the same possible transitions.
Usage
normalizedEntropyRate(object)
## S4 method for signature 'markovchain'
normalizedEntropyRate(object)
Arguments
object |
A |
Details
The ratio H / h_{top} does not depend on the logarithm base, so no
base argument is needed. By the variational principle
(topologicalEntropy) it never exceeds one; tiny excursions
due to round-off are clipped to [0,1]. When h_{top}=0 the
chain has a single possible path, hence entropy rate zero, and the
ratio is defined here to be 0, the convention used by PyDTMC's
entropy_rate_normalized.
Irreducibility is required, as in entropyRate, which is
what makes the entropy rate well defined.
Value
A numeric scalar in [0,1]: 0 for deterministic
dynamics, 1 when the entropy rate reaches the topological
entropy.
See Also
entropyRate, topologicalEntropy
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
normalizedEntropyRate(mc)
Returns an Identity matrix
Description
Returns an Identity matrix
Usage
ones(n)
Arguments
n |
size of the matrix |
Value
a identity matrix
Structural analysis of a Markov chain
Description
Classification of the states of a Markov chain from the graph of its possible transitions: communicating, recurrent and transient classes and states, absorbing states, the canonical form of the transition matrix, and the period.
Usage
period(object)
communicatingClasses(object)
recurrentClasses(object)
transientClasses(object)
transientStates(object)
recurrentStates(object)
absorbingStates(object)
canonicForm(object)
Arguments
object |
A |
Value
periodreturns an integer, the period of the Markov chain (the greatest common divisor of the lengths of its cycles); it is defined for an irreducible chain (otherwise a warning is given and 0 is returned)
absorbingStatesreturns a character vector with the names of the absorbing states in the Markov chain
communicatingClassesreturns a list in which each slot contains the names of the states that are in that communicating class
recurrentClassesanalogously to
communicatingClasses, but with recurrent classestransientClassesanalogously to
communicatingClasses, but with transient classestransientStatesreturns a character vector with all the transient states for the Markov chain
recurrentStatesreturns a character vector with all the recurrent states for the Markov chain
canonicFormreturns the Markov chain reordered by a permutation of states so that we have blocks submatrices for each of the recurrent classes and a collection of rows in the end for the transient states
Author(s)
Giorgio Alfredo Spedicato, Ignacio Cordón
References
Feres, Matlab listing for markov chain.
See Also
Examples
statesNames <- c("a", "b", "c")
mc <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3,
0, 1, 0,
0.1, 0.8, 0.1), nrow = 3, byrow = TRUE,
dimnames = list(statesNames, statesNames))
)
communicatingClasses(mc)
recurrentClasses(mc)
transientClasses(mc)
absorbingStates(mc)
transientStates(mc)
recurrentStates(mc)
canonicForm(mc)
# periodicity analysis
A <- matrix(c(0, 1, 0, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0, 0.5, 0, 0, 1, 0),
nrow = 4, ncol = 4, byrow = TRUE)
mcA <- new("markovchain", states = c("a", "b", "c", "d"),
transitionMatrix = A,
name = "A")
is.irreducible(mcA) #true
period(mcA) #2
# periodicity analysis
B <- matrix(c(0, 0, 1/2, 1/4, 1/4, 0, 0,
0, 0, 1/3, 0, 2/3, 0, 0,
0, 0, 0, 0, 0, 1/3, 2/3,
0, 0, 0, 0, 0, 1/2, 1/2,
0, 0, 0, 0, 0, 3/4, 1/4,
1/2, 1/2, 0, 0, 0, 0, 0,
1/4, 3/4, 0, 0, 0, 0, 0), byrow = TRUE, ncol = 7)
mcB <- new("markovchain", transitionMatrix = B)
period(mcB)
Plot state sequences of a Markov chain
Description
Draws simulated or observed trajectories of a Markov chain either as a sequence index plot (each sequence a row of coloured cells, one per time point) or as a state distribution plot (the proportion of sequences in each state at each time point), optionally with the distribution expected from a chain overlaid.
Usage
plotSequence(
x,
type = c("index", "distribution"),
nSequences = 20L,
steps = 50L,
initial = NULL,
chain = NULL,
sort = c("none", "first", "last"),
expected = TRUE,
col = NULL,
legend = TRUE,
main = NULL,
xlab = "Time",
ylab = NULL,
seed = NULL,
...
)
Arguments
x |
A |
type |
|
nSequences, steps |
For a |
initial |
For a |
chain |
For observed data, an optional |
sort |
For |
expected |
For |
col |
Optional vector of colours, one per state. The default is
|
legend |
Whether to draw a legend of the states (default
|
main, xlab, ylab |
Title and axis labels. |
seed |
For a |
... |
Further graphical parameters passed to |
Details
Sequence index plots and state distribution plots are the two basic
graphs of sequence analysis (Gabadinho et al. 2011). For a Markov chain
the first shows the lengths of the spells in each state and the second
how the distribution of the state moves towards the stationary
distribution. The expected distribution at time t is
\mu_1 P^{t-1}, with \mu_1 the observed (or, for a
markovchain x, the given) initial distribution, computed by
redistribute; with observed data a systematic gap between the
two suggests that the chain is not time-homogeneous (see
assessStationarity). The proportions at each time point
are computed over the sequences observed at that time point.
The sequences of a markovchain are simulated in C++ by inversion of
the cumulative probabilities with R's uniform generator, so set.seed
and seed control them. The plot is drawn with base graphics. The legend is placed in the right
margin, which is widened for the purpose and restored afterwards.
Value
Invisibly, a list with sequences, the character matrix of
the sequences as plotted (one row per sequence, after sorting);
proportions, the matrix of the observed proportion of each state
(rows) at each time point (columns); and expected, the matching
matrix of expected proportions, or NULL when no chain is
available.
References
Gabadinho, A., Ritschard, G., Mueller, N. S. and Studer, M. (2011). Analyzing and visualizing state sequences in R with TraMineR. Journal of Statistical Software, 40(4), 1-37. doi:10.18637/jss.v040.i04
See Also
rmarkovchain, redistribute,
autoplot.markovchain (type = "flow")
Examples
s <- c("sunny", "cloudy", "rain")
weather <- new("markovchain", states = s, transitionMatrix = matrix(
c(0.7, 0.2, 0.1, 0.3, 0.4, 0.3, 0.2, 0.45, 0.35), 3, byrow = TRUE,
dimnames = list(s, s)))
plotSequence(weather, nSequences = 30, steps = 40, initial = "rain", seed = 1)
plotSequence(weather, type = "distribution", nSequences = 200, steps = 15,
initial = "rain", seed = 1)
# observed trajectories, sorted by their first state, and their
# distribution against a time-homogeneous chain fitted to them
data(holson)
plotSequence(holson[1:60, 2:12], sort = "first")
fitted <- markovchainFit(holson[, 2:12])$estimate
plotSequence(holson[, 2:12], type = "distribution", chain = fitted)
Build a population-genetics Markov chain (Moran or Wright-Fisher)
Description
Constructs the Markov chain tracking the number of copies of a mutant
allele in a population of n individuals under mutation and
viability selection, for either the Moran or the Wright-Fisher model of
population genetics.
Usage
populationGeneticsModel(
model = c("moran", "wright-fisher"),
n,
s = 0,
u = 1e-09,
v = 1e-09,
states = NULL
)
Arguments
model |
Either |
n |
A single integer of at least |
s |
A single finite number greater than |
u |
A single number in |
v |
A single number in |
states |
An optional character vector of |
Details
Moran model. At each step one individual is chosen to reproduce
(with probability proportional to its type's relative fitness, mutant
fitness r=1+s against wild-type fitness 1) and one
individual, chosen uniformly at random, dies and is replaced by the
offspring, which mutates with probability u or v
depending on the parent's type. From interior state i
(0<i<n), writing r_i=(1+s)i and m_i=n-i,
P_{i,i-1}=\frac{i}{n}\cdot\frac{r_i v + m_i(1-u)}{r_i+m_i},\qquad
P_{i,i+1}=\frac{m_i}{n}\cdot\frac{r_i(1-u) + m_i v}{r_i+m_i},
with P_{ii} the remainder.
Wright-Fisher model. Generations are discrete and
non-overlapping: from interior state i, the mutant-allele
frequency k=i/n is first updated for mutation,
p=k(1-u)+(1-k)v, then for viability selection,
p'=\min\bigl(p(1+s)/(1+ps),\,1\bigr), and the next generation's
mutant count is \mathrm{Binomial}(n,p')-distributed:
P_{ij}=\binom{n}{j}p'^{\,j}(1-p')^{n-j}.
Both constructions follow PyDTMC's
population_genetics_model, with two deliberate differences. First, this
function uses mutant relative fitness 1+s in both models
(PyDTMC's Moran implementation instead uses 1-s, so that a
positive s there favours the wild-type rather than the mutant,
the opposite of its own Wright-Fisher convention and of the usual
textbook one). Second, in the mutation terms: for
u != v the probability P_{i,i-1} follows the description of
the model (a mutant parent has a wild-type offspring with probability
u, a wild-type parent with probability 1-v), whereas
PyDTMC uses r_i v in place of r_i u in the numerator, which
makes its chain depend on how the two alleles are labelled; for
u = v (the default) the two coincide. With s = 0 and
u = v the two packages' Moran chains are identical; otherwise they
differ by construction, by design (for s, to keep its meaning
consistent between "moran" and "wright-fisher" within this
package). As u, v shrink to
0, both reduce to the classical drift-only chains with absorbing
loss/fixation states, going back to Wright (1931) and Moran (1958); see
Ewens (2004) for a modern textbook treatment of both.
Value
A new, row-stochastic markovchain object on n + 1
states. States "0" and as.character(n) (loss and
fixation of the mutant allele) are absorbing, following the standard
textbook treatment of both models; every interior state has a
transition row determined by model, s, u and
v as detailed below.
References
Wright, S. (1931). Evolution in Mendelian populations. Genetics, 16(2), 97-159.
Moran, P. A. P. (1958). Random processes in genetics. Mathematical Proceedings of the Cambridge Philosophical Society, 54(1), 60-71.
Ewens, W. J. (2004). Mathematical Population Genetics I: Theoretical Introduction (2nd ed.). Springer.
See Also
Examples
# Neutral drift (s = 0): absorption ("fixation") probability of the
# mutant allele from state i equals i/n, the classical result.
neutral <- populationGeneticsModel(model = "moran", n = 8, s = 0)
ap <- absorptionProbabilities(neutral)
ap["4", "8"] # close to 4/8 = 0.5
# Positive selection increases the fixation probability from any
# interior starting count.
favoured <- populationGeneticsModel(model = "wright-fisher", n = 8, s = 0.5)
absorptionProbabilities(favoured)["4", "8"]
Simulate from a higher order multivariate Markov chain
Description
Simulates the next t states of each sequence of a higher
order multivariate Markov chain, given their last order states.
Usage
predictHommc(hommc, t, init)
Arguments
hommc |
An |
t |
Number of steps to simulate, a positive integer. |
init |
A matrix with one row per sequence and |
Details
At each step the next state of sequence j is drawn from
\sum_k \sum_h \lambda_{jkh} P_h^{(jk)} x^{(k)}_{t-h+1}, where
x^{(k)}_{t-h+1} is the state of sequence k h - 1
steps before the current one (Ching et al., 2008). The matrices are read
by column (P[to, from]), as returned by fitHighOrderMultivarMC(), or
by row when the byrow slot of hommc is TRUE; all the sequences are
drawn from the same past before it is updated.
Value
A character matrix with one row per sequence and t columns, the
simulated states.
Author(s)
Vandit Jain
References
Ching, W.-K., Ng, M. K. and Fung, E. S. (2008). Higher-order multivariate Markov chains and their applications. Linear Algebra and its Applications 428(2-3), 492-507. doi:10.1016/j.laa.2007.05.021
See Also
Other higher order chains:
fitHighOrderMultivarMC(),
fitHigherOrder()
Examples
data <- matrix(c("2", "1", "3", "3", "4", "3", "2", "1", "3", "3", "2", "1",
"2", "4", "4", "4", "4", "2", "3", "3", "1", "4", "3", "3"),
ncol = 2)
if (requireNamespace("Rsolnp", quietly = TRUE)) {
fit <- fitHighOrderMultivarMC(data, order = 2, Norm = 2)
# the last two states of each sequence
init <- t(data[11:12, ])
predictHommc(fit, 5, init)
}
Bayesian predictive probability of new data
Description
Log-probability of observing the sequence newData after
the sequence stringchar, under a first-order Markov chain whose rows
have independent Dirichlet priors: the likelihood of newData averaged
over the posterior given stringchar.
Usage
predictiveDistribution(stringchar, newData, hyperparam = matrix())
Arguments
stringchar |
The observed sequence of states on which the posterior is based (a character vector). |
newData |
The sequence whose predictive probability is computed. |
hyperparam |
Matrix of Dirichlet hyperparameters, one row per state, with the states as dimnames (in any order). The default, an empty matrix, sets all of them to 1 (uniform priors). |
Details
With conjugate Dirichlet priors the predictive probability has a closed form, a ratio of products of gamma functions (Strelioff et al. 2007), which is what is computed.
Value
A number, the logarithm of the predictive probability.
Author(s)
Sai Bhargav Yalamanchi
References
Strelioff, C. C., Crutchfield, J. P. and Hubler, A. W. (2007). Inferring Markov chains: Bayesian estimation, model comparison, entropy rate, and out-of-class modeling. Physical Review E 76, 011106. doi:10.1103/PhysRevE.76.011106
Yalamanchi, S. B. and Spedicato, G. A. (2015). Bayesian inference of first order Markov chains. Vignette of the markovchain package.
See Also
Other Bayesian inference:
inferHyperparam(),
priorDistribution()
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)
predProb
# the order of the states in the hyperparameter matrix does not matter
hyperMatrix2 <- hyperMatrix[c(2, 1), c(2, 1)]
predictiveDistribution(sequence[1:10], sequence[11:17],
hyperparam = hyperMatrix2) == predProb
Preprogluccacon DNA protein bases sequences
Description
Sequence of bases for preproglucacon DNA protein
Usage
data(preproglucacon)
Format
A data frame with 1572 observations on the following 2 variables.
V1a numeric vector, showing original coding
preproglucacona character vector, showing initial of DNA bases (Adenine, Cytosine, Guanine, Thymine)
Source
Avery Henderson
References
Averuy Henderson, Fitting markov chain models on discrete time series such as DNA sequences
Examples
data(preproglucacon)
preproglucaconMc<-markovchainFit(data=preproglucacon$preproglucacon)
Print bootstrap intervals for a Markov chain
Description
Print bootstrap intervals for a Markov chain
Usage
## S3 method for class 'markovchainBootstrap'
print(x, digits = 4, ...)
Arguments
x |
A |
digits |
Number of significant digits. |
... |
Passed to |
Value
x, invisibly.
Print a comparison of two Markov chains
Description
Print a comparison of two Markov chains
Usage
## S3 method for class 'markovchainComparison'
print(x, digits = 4, ...)
Arguments
x |
A |
digits |
Number of significant digits. |
... |
Passed to |
Value
x, invisibly.
Prior density of a transition matrix
Description
Log-density of each row of a transition matrix under independent Dirichlet priors, the conjugate priors used by the Bayesian estimation of the package.
Usage
priorDistribution(transMatr, hyperparam = matrix())
Arguments
transMatr |
The transition matrix, with the states as dimnames. |
hyperparam |
Matrix of Dirichlet hyperparameters, with the states as dimnames (in any order). The default, an empty matrix, sets all of them to 1, the uniform prior. |
Value
A named numeric vector with, for each state, the logarithm of the
Dirichlet density of its row of transMatr.
Note
With a prior data set and a prior transition matrix, the
hyperparameters can be inferred with inferHyperparam() and the prior
density of the matrix then evaluated with these hyperparameters.
Author(s)
Sai Bhargav Yalamanchi, Giorgio Spedicato
References
Yalamanchi, S. B. and Spedicato, G. A. (2015). Bayesian inference of first order Markov chains. Vignette of the markovchain package.
See Also
Other Bayesian inference:
inferHyperparam(),
predictiveDistribution()
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"))))
Transition probabilities of a continuous time Markov chain at time t
Description
Computes the transition matrix P(t) = \exp(t Q) of a
continuous time Markov chain with generator Q, or one of its rows.
Usage
probabilityatT(C, t, x0, useRCpp = TRUE)
Arguments
C |
A |
t |
Time, a non-negative number. |
x0 |
Optional index (position in |
useRCpp |
Logical: compute the matrix exponential in C++ (default) or
with |
Value
Without x0, the matrix P(t), with the states as dimnames,
whose entry (i, j) is the probability of being in state j at time
t when starting from i. With x0, row x0 of that matrix: the
distribution of the state at time t when starting from x0.
Author(s)
Vandit Jain
References
Dobrow, R. P. (2016). Introduction to Stochastic Processes with R. Wiley.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
rctmc(),
transition2Generator()
Examples
states <- c("a", "b", "c", "d")
gen <- matrix(c(-1, 1/2, 1/2, 0,
1/4, -1/2, 0, 1/4,
1/6, 0, -1/3, 1/6,
0, 0, 0, 0), nrow = 4, byrow = TRUE,
dimnames = list(states, states))
ctmc <- new("ctmc", states = states, byrow = TRUE, generator = gen,
name = "testctmc")
probabilityatT(ctmc, 1)
probabilityatT(ctmc, 1, x0 = 1)
Alofi island daily rainfall
Description
Rainfall measured in Alofi Island
Usage
data(rain)
Format
A data frame with 1096 observations on the following 2 variables.
V1a numeric vector, showing original coding
raina character vector, showing daily rainfall millilitres brackets
Source
Avery Henderson
References
Avery Henderson, Fitting markov chain models on discrete time series such as DNA sequences
Examples
data(rain)
rainMc<-markovchainFit(data=rain$rain)
Random Markov chain
Description
Generates a Markov chain whose transition probabilities are drawn at random, optionally with a given number of zero probabilities and with some probabilities fixed in advance.
Usage
randomMarkovChain(
n,
states = NULL,
zeros = 0L,
mask = NULL,
byrow = TRUE,
seed = NULL,
name = "Random Markov chain"
)
Arguments
n |
The number of states. It can be omitted when |
states |
An optional character vector of |
zeros |
The number of transition probabilities, among those not
fixed by |
mask |
An optional |
byrow |
Whether the transition matrix of the result is stored by rows (the default) or by columns. |
seed |
An optional whole number. When given, the chain is generated
after |
name |
The |
Details
The algorithm follows MarkovChain.random() of PyDTMC. In each row
not completely fixed by mask, one free entry, chosen at random, is
reserved to be positive. The zeros zero entries are then chosen at
random among the remaining free entries of the whole matrix, the other
free entries are drawn from a uniform distribution on (0, 1), and
the free entries of each row are rescaled so that, together with the
fixed ones, they sum to one. The rows are normalised uniforms, which is
not the uniform distribution on the simplex; use
dirichletChain or draw the rows yourself if that matters.
Value
A markovchain object with n states.
See Also
Examples
randomMarkovChain(4, seed = 1)
# 6 of the 16 transition probabilities are zero
sum(randomMarkovChain(4, zeros = 6, seed = 1)@transitionMatrix == 0)
# state "b" moves to "a" with probability 0.5; the rest is random
m <- matrix(NA, 3, 3)
m[2, 1] <- 0.5
randomMarkovChain(states = c("a", "b", "c"), mask = m, seed = 1)
Simulate a continuous time Markov chain
Description
Simulates the jumps of a continuous time Markov chain: in each
state i the chain waits an exponential time with rate
-Q_{ii}, then jumps to j \ne i with probability
-Q_{ij} / Q_{ii} (the embedded jump chain, see
generatorToTransitionMatrix()).
Usage
rctmc(
n,
ctmc,
initDist = numeric(),
T = 0,
include.T0 = TRUE,
out.type = "list"
)
Arguments
n |
Number of jumps to simulate: a positive integer, or |
ctmc |
A |
initDist |
Distribution of the initial state, a probability vector in
the order of |
T |
Time horizon: the jumps after time |
include.T0 |
Logical: include the initial state, at time 0, in the output? |
out.type |
|
Details
The simulation stops after n jumps, at the first jump after
T (when T > 0), or when an absorbing state (zero exit rate) is
reached, whichever comes first. The generator is used in the orientation
given by the byrow slot of ctmc.
Value
With out.type = "list", an unnamed list of two vectors of equal
length: the states visited (character) and the times at which they were
entered (numeric). With out.type = "df", a data frame with the same
content in the columns states and time.
Author(s)
Sai Bhargav Yalamanchi
References
Anderson, D. F. (2013). Introduction to Stochastic Processes with Applications in the Biosciences. University of Wisconsin at Madison.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
transition2Generator()
Examples
energyStates <- c("sigma", "sigma_star")
gen <- matrix(c(-3, 3, 1, -1), nrow = 2, byrow = TRUE,
dimnames = list(energyStates, energyStates))
molecularCTMC <- new("ctmc", states = energyStates, byrow = TRUE,
generator = gen, name = "Molecular Transition Model")
# all the jumps up to time 1
rctmc(n = Inf, ctmc = molecularCTMC, T = 1)
# five jumps from an initial state drawn from c(0.8, 0.2)
rctmc(n = 5, ctmc = molecularCTMC, initDist = c(0.8, 0.2),
include.T0 = FALSE, out.type = "df")
Evolution of a distribution over time
Description
Propagates an initial distribution of the states of a discrete-time Markov chain forward in time and returns the whole trajectory of distributions.
Usage
redistribute(object, steps, initial = NULL, lastOnly = FALSE)
## S4 method for signature 'markovchain'
redistribute(object, steps, initial = NULL, lastOnly = FALSE)
Arguments
object |
A |
steps |
A single non-negative whole number: the number of steps to
propagate. With |
initial |
The initial distribution. Either |
lastOnly |
Logical. If |
Details
If \mu_0 is the initial distribution (a row vector) and P the
row-stochastic transition matrix, the distribution after t steps is
\mu_t = \mu_{t-1} P = \mu_0 P^t.
The implementation propagates the vector step by step, at a cost of
O(n^2) per step for a dense n-state chain, instead of
forming P^t; this is what makes the whole trajectory available at
no extra cost. Both row- and column-stochastic storage are supported.
Each distribution is renormalized after every step to prevent round-off
from accumulating over long horizons.
This mirrors PyDTMC's redistribute(), with the same defaults
(uniform initial distribution, output including the initial one).
For chains that converge, the rows approach the stationary distribution
(see steadyStates); for periodic chains they do not, which is
the expected behaviour and not an error.
Value
If lastOnly = FALSE (default), a numeric matrix with
steps + 1 rows and one column per state: row t (labelled
"t", from "0") holds the distribution after t
steps, so the first row is the initial distribution. Otherwise, a named
numeric vector with the distribution after steps steps.
See Also
steadyStates, mixingTime,
autoplot.markovchain
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
redistribute(mc, steps = 5, initial = "a")
redistribute(mc, steps = 50, initial = c(a = 0.2, b = 0.8), lastOnly = TRUE)
Relaxation time of a Markov chain
Description
The relaxation time 1/\mathrm{gap} of a finite irreducible
discrete-time Markov chain, the reciprocal of its spectral gap.
Usage
relaxationTime(object)
## S4 method for signature 'markovchain'
relaxationTime(object)
Arguments
object |
A |
Details
Following Levin and Peres (2017, Section 12.2) the relaxation time is
t_{rel} = 1/\gamma, with \gamma = 1 - \mathrm{SLEM} the
spectral gap of spectralGap. It is the quantity PyDTMC
calls relaxation_rate, even if it is a time, not a rate. The
two are the same number.
PyDTMC's mixing_rate is -1/\log(\mathrm{SLEM}), i.e. the
timescale of the slowest non-trivial mode, which is already returned
as the first element ("tau2") of impliedTimescales.
It is therefore not repeated as a separate function.
Value
A positive numeric scalar, in number of steps: Inf for a
periodic chain (spectral gap zero), 1 for the trivial one-state
chain.
References
Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times, 2nd edition. American Mathematical Society.
See Also
spectralGap, slem,
impliedTimescales, mixingTime
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
relaxationTime(mc)
Simulate from a homogeneous or non-homogeneous Markov chain
Description
Simulates trajectories of a homogeneous Markov chain (a
markovchain object) or of a non-homogeneous one (a
markovchainList object, whose k-th
matrix gives the transition from time k - 1 to time k).
Usage
rmarkovchain(
n,
object,
what = "data.frame",
useRCpp = TRUE,
parallel = FALSE,
num.cores = NULL,
...
)
Arguments
n |
For a |
object |
A |
what |
Form of the output for a |
useRCpp |
Logical: use the C++ implementation (default)? |
parallel |
Logical: simulate the trajectories of a |
num.cores |
Number of threads used when |
... |
Further arguments: |
Details
For a markovchain the function calls markovchainSequence().
For a markovchainList each trajectory starts from t0 (by default a
state drawn at random) and moves once with each matrix of the list.
Value
For a markovchain, a character vector of states. For a
markovchainList, a data frame, matrix or list, according to what.
Author(s)
Giorgio Spedicato
References
Ross, S. (2010). A First Course in Probability (8th edition). Prentice Hall.
See Also
markovchainFit() and markovchainListFit() for the reverse
operation.
Other simulation:
markovchainSequence()
Examples
statesNames <- c("a", "b", "c")
mcA <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames = list(statesNames, statesNames)))
rmarkovchain(n = 20, object = mcA, t0 = "a")
# a non-homogeneous chain: a different matrix at each of three steps
mcB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.5, 0.5, 0, 0.1, 0.8, 0.1, 0, 0.5, 0.5), nrow = 3,
byrow = TRUE, dimnames = list(statesNames, statesNames)))
mclist <- new("markovchainList", markovchains = list(mcA, mcB, mcA))
rmarkovchain(5, mclist, what = "matrix")
rmarkovchain(2, mclist, what = "list", t0 = "a", include.t0 = TRUE)
Discretize an AR(1) process into a Markov chain (Rouwenhorst's method)
Description
Approximates the stationary first-order autoregressive process
y_t = (1-\rho)\alpha + \rho y_{t-1} + \varepsilon_t, \qquad
\varepsilon_t \overset{\mathrm{iid}}{\sim} \mathcal N(0,\sigma^2)
by a finite-state Markov chain, following Rouwenhorst (1995). Unlike
tauchen, no grid-width parameter is needed and the method
remains accurate for rho close to \pm 1.
Usage
rouwenhorst(alpha, sigma, rho, size)
Arguments
alpha |
A single finite number: the unconditional mean of the process. |
sigma |
A single finite positive number: the standard deviation of
the innovation |
rho |
A single number in |
size |
A single integer of at least |
Details
The grid is n=\code{size} evenly spaced points spanning
[\alpha-\psi,\ \alpha+\psi] with
\psi=\sigma_y\sqrt{n-1}, where
\sigma_y=\sigma/\sqrt{1-\rho^2} is the process's unconditional
standard deviation: this particular width (rather than a fixed multiple
of \sigma_y as in tauchen) is what the method needs
in order to match the AR(1)'s variance and first-order autocorrelation
exactly at every size, including for rho near \pm1.
The transition matrix is built recursively. Let
\theta=(1+\rho)/2 and, for two states,
\Theta_2 = \begin{pmatrix}\theta & 1-\theta\\ 1-\theta & \theta\end{pmatrix}.
For m states (2<m\le n), form the m\times m matrix
\Theta_m = \theta\begin{pmatrix}\Theta_{m-1} & 0\\ 0 & 0\end{pmatrix}
+ (1-\theta)\begin{pmatrix}0 & \Theta_{m-1}\\ 0 & 0\end{pmatrix}
+ (1-\theta)\begin{pmatrix}0 & 0\\ \Theta_{m-1} & 0\end{pmatrix}
+ \theta\begin{pmatrix}0 & 0\\ 0 & \Theta_{m-1}\end{pmatrix},
then divide every interior row (all but the first and last) by 2
to restore row-stochasticity, since those rows receive contributions
from two of the four corner blocks above.
Rouwenhorst's method reproduces the AR(1)'s unconditional variance and
lag-1 autocorrelation \rho exactly, for every size
(Kopecky and Suen (2010) find it outperforms tauchen and
several other methods across the persistence range typically seen in
quarterly macroeconomic and actuarial time series, e.g. discretized
short-rate or inflation processes for reserving and ALM work).
Value
A named list with two elements, chain and states,
in the same form as returned by tauchen.
References
Rouwenhorst, K. G. (1995). Asset pricing implications of equilibrium business cycle models. In T. F. Cooley (Ed.), Frontiers of Business Cycle Research, 294-330. Princeton University Press.
Kopecky, K. A. and Suen, R. M. H. (2010). Finite state Markov-chain approximations to highly persistent processes. Review of Economic Dynamics, 13(3), 701-714.
See Also
Examples
out <- rouwenhorst(alpha = 0, sigma = 1, rho = 0.9, size = 5)
out$states
pi <- as.numeric(steadyStates(out$chain))
sum(pi * (out$states - sum(pi * out$states))^2) # matches 1/(1-rho^2) closely
1 / (1 - 0.9^2)
Sales Demand Sequences
Description
Sales demand sequences of five products (A, B, C, D, E). Each row corresponds to a sequence. First row corresponds to Sequence A, Second row to Sequence B and so on.
Usage
data("sales")
Format
An object of class matrix (inherits from array) with 269 rows and 5 columns.
Details
The example can be used to fit High order multivariate markov chain.
Examples
data("sales")
# fitHighOrderMultivarMC(seqMat = sales, order = 2, Norm = 2)
Select the order of a Markov chain by information criteria
Description
Fits by maximum likelihood fully parameterized Markov chains of
order 0, 1, \dots, maxOrder to an empirical sequence (or to a
list of independent sequences), all on the same observations, and selects
the order that minimizes the BIC or the AIC (Tong, 1975; Katz, 1981).
Usage
selectOrder(
sequence,
maxOrder = 3,
criterion = c("BIC", "AIC"),
start = NULL,
parameters = c("full", "observed")
)
Arguments
sequence |
An empirical sequence of states (a vector coercible to character, without missing values), or a list of such sequences. |
maxOrder |
The highest order considered, a non-negative integer. |
criterion |
The criterion used to select the order: |
start |
Index of the first observation of each sequence entering the
likelihood, at least |
parameters |
How the free parameters are counted: |
Details
A Markov chain of order k on r states has a transition
probability for each context (the k previous states) and next state;
order 0 is independence. Its maximum likelihood estimates are the observed
transition frequencies, and its log-likelihood is
\sum N(c, j) \log\{N(c, j) / N(c)\}, where N(c, j) counts
context c followed by state j.
Information criteria are only comparable when every model is evaluated on
the same observations. An order-k chain can only predict an
observation from position k + 1 onwards, so all orders are
evaluated on the observations from start (by default
maxOrder + 1) to the end of each sequence, the earlier ones being
only used as contexts. Berchtold and Raftery (2002), for instance, condition
on the first 14 observations (start = 15). For a list of sequences
the counts are pooled, the observations before start of each
sequence are only used as contexts, and no context crosses from one
sequence to the next.
With parameters = "full" (the default) an order-k chain has
r^k (r - 1) free parameters, as in Tong (1975) and Katz (1981).
With parameters = "observed" only the probabilities that are not
estimated as zero are counted, that is the number of distinct next states
minus one summed over the observed contexts; this is the convention of
Berchtold and Raftery (2002), which is less penalizing when many
transitions are never observed. In both cases BIC uses the number of
observations entering the likelihood.
The table also reports the likelihood-ratio statistic of each order
against the previous one, G = 2 (\ell_k - \ell_{k-1}), with degrees
of freedom equal to the difference in the number of parameters and an
asymptotic chi-squared p-value (Anderson and Goodman, 1957). With
parameters = "observed" the degrees of freedom are the differences
of the observed counts, that is transitions never observed are treated as
structurally impossible, the usual adjustment for sparse tables (it is
the one of assessOrder) but an approximate one, since a zero
count may be a sampling zero: the p-values are then indicative only. These
tests are not adjusted for multiplicity, and they and the criteria become
unreliable when the number of contexts r^k is not small compared with
the number of observations: BIC is consistent for the order (Csiszar and
Shields, 2000), whereas AIC tends to select too high an order in long
sequences (Katz, 1981).
Value
A list with components
order |
the order selected by |
criterion |
the criterion used |
table |
a data frame with one row per order: |
nobs |
number of observations entering the likelihood |
start, parameters |
as used |
References
Anderson, T. W. and Goodman, L. A. (1957). Statistical inference about Markov chains. The Annals of Mathematical Statistics, 28(1), 89-110.
Tong, H. (1975). Determination of the order of a Markov chain by Akaike's information criterion. Journal of Applied Probability, 12(3), 488-497.
Katz, R. W. (1981). On some criteria for estimating the order of a Markov chain. Technometrics, 23(3), 243-249.
Csiszar, I. and Shields, P. C. (2000). The consistency of the BIC Markov order estimator. The Annals of Statistics, 28(6), 1601-1619.
Berchtold, A. and Raftery, A. E. (2002). The mixture transition distribution model for high-order Markov chains and non-Gaussian time series. Statistical Science, 17(3), 328-356.
See Also
assessOrder, verifyMarkovProperty,
fitHigherOrder, fitMTD,
higherOrderLogLik
Examples
# Alofi rainfall: three states
data(rain)
selectOrder(rain$rain, maxOrder = 3)$table
# Koeberg wind directions with the conventions of Berchtold and Raftery (2002)
wind <- read.csv(system.file("extdata", "koeberg_wind.csv",
package = "markovchain"))$state
sel <- selectOrder(wind, maxOrder = 3, start = 15, parameters = "observed")
sel$order
sel$table
Sensitivity of the stationary distribution to a state's transition row
Description
Computes, for a finite, irreducible discrete-time Markov chain, the coefficients needed to obtain the first-order change in the stationary distribution caused by an infinitesimal perturbation of one row of the transition matrix.
Usage
sensitivity(object, state)
## S4 method for signature 'markovchain'
sensitivity(object, state)
Arguments
object |
A |
state |
A single state name (character) or state index (single
positive integer), identifying the row |
Details
A single entry p_{kl} of a stochastic matrix cannot be perturbed on
its own without leaving row k: some other entry (or entries) of that
row must move to compensate, so that the row still sums to one. Any
admissible perturbation of row k is therefore a direction vector
d\in\mathbb{R}^n with \sum_l d_l = 0, giving the perturbed
matrix P(\varepsilon) = P + \varepsilon\, e_k d^{\mathsf T} for small
\varepsilon. This function returns the n\times n matrix
S such that, for every such d and every state j,
\left.\frac{d\pi_j}{d\varepsilon}\right|_{\varepsilon=0} =
\sum_l d_l\, S_{lj} = \left(d^{\mathsf T} S\right)_j.
Closed form. Let Z=(I-P+\mathbf 1\pi^{\mathsf T})^{-1} be
the fundamental matrix already used by kemenyConstant. Then
S_{lj} = \pi_k\left(Z_{lj} - \pi_j\right).
This particular centering (subtracting \pi_j, the same constant for
every row l) is what makes S usable directly with any
zero-sum direction d, because \sum_l d_l \pi_j = \pi_j\sum_l
d_l = 0 drops out of the sum above – adding any other per-column
constant to S would give the same directional derivatives, but this
one has the convenient side effect that sensitivity(object,
state)[state, ] is the sensitivity of "leaving row state
unchanged", which is informative on its own (it need not be zero: the
direction d=e_{\mathrm{state}} is generally not itself a valid
zero-sum perturbation by itself, only differences of rows are).
The common two-state case. The usual textbook question –
"increase p_{k,\mathrm{to}} by \varepsilon, decrease
p_{k,\mathrm{from}} by \varepsilon, how does \pi move?"
– is answered by taking the difference of two rows of S:
\left.\frac{d\pi}{d\varepsilon}\right|_{\varepsilon=0} =
S_{\mathrm{to}, \cdot} - S_{\mathrm{from}, \cdot}.
See the second example below, which checks this against a direct finite-difference recomputation of the stationary distribution.
Only irreducibility is required, not aperiodicity: Z and \pi
are well defined for any irreducible chain regardless of periodicity.
The implementation calls steadyStates once and then solves
one dense linear system for Z; both are O(n^3) time and
O(n^2) memory for a dense n-state transition matrix, the same
cost as kemenyConstant. It supports both row- and
column-stochastic storage; S is always returned with rows/columns
indexed by state name in the chain's own state order.
Value
An n\times n numeric matrix S, with both dimensions
named after states(object). Row l of S corresponds to
the perturbation direction "increase p_{kl}" (paired with a
compensating decrease elsewhere in row k); column j
corresponds to the affected stationary probability \pi_j. See
Details for how to read individual entries.
References
Schweitzer, P. J. (1968). Perturbation theory and finite Markov chains. Journal of Applied Probability, 5(2), 401-413.
Meyer, C. D. (1980). The condition of a finite Markov chain and perturbation bounds for the limiting probabilities. SIAM Journal on Algebraic and Discrete Methods, 1(3), 273-283.
Cho, G. E. and Meyer, C. D. (2001). Comparison of perturbation bounds for the stationary distribution of a Markov chain. Linear Algebra and its Applications, 335(1-3), 137-150.
See Also
kemenyConstant, steadyStates,
is.irreducible
Examples
statesNames <- c("a", "b", "c")
mc <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.5, 0.3, 0.2,
0.2, 0.6, 0.2,
0.1, 0.1, 0.8), byrow = TRUE, nrow = 3,
dimnames = list(statesNames, statesNames)))
S <- sensitivity(mc, "a")
S
# Check against a finite-difference recomputation of the stationary
# distribution: increase p("a"->"c") and decrease p("a"->"b") by eps.
eps <- 1e-6
P2 <- mc@transitionMatrix
P2["a", "c"] <- P2["a", "c"] + eps
P2["a", "b"] <- P2["a", "b"] - eps
mc2 <- new("markovchain", states = statesNames, transitionMatrix = P2)
(steadyStates(mc2) - steadyStates(mc)) / eps # finite difference
S["c", ] - S["b", ] # closed-form prediction
Function to display the details of hommc object
Description
This is a convenience function to display the slots of hommc object in proper format
Usage
## S4 method for signature 'hommc'
show(object)
Arguments
object |
An object of class hommc |
Second largest eigenvalue modulus (SLEM) of a Markov chain
Description
Computes the second largest eigenvalue modulus (SLEM) of a finite, irreducible discrete-time Markov chain.
Usage
slem(object)
## S4 method for signature 'markovchain'
slem(object)
Arguments
object |
A |
Details
For a row-stochastic transition matrix P, let
1=\lambda_1,\lambda_2,\ldots,\lambda_n be its eigenvalues. By the
Perron-Frobenius theorem an irreducible chain has \lambda_1=1 with
algebraic multiplicity one, and |\lambda_k|\le 1 for every
k. The SLEM is
\mathrm{SLEM} = \max_{k>1} |\lambda_k|.
Only irreducibility is required, not aperiodicity. If the chain is
periodic, at least one non-trivial eigenvalue also has modulus one (e.g.
\lambda=-1 for a 2-cycle), so slem() correctly returns
1 rather than rejecting the chain: a periodic chain genuinely does
not contract towards its stationary distribution, which SLEM = 1
reflects.
Repeated or complex non-trivial eigenvalues are handled through their
modulus Mod(), so complex-conjugate pairs contribute the same
value and ties do not need to be broken.
The implementation calls eigen() with only.values = TRUE,
so it never computes eigenvectors. Its time complexity is
O(n^3) and its memory use is O(n^2) for a dense n-state
transition matrix. It supports both row- and column-stochastic storage.
The eigenvalues are kept in a session cache, so other spectral functions
called on the same chain do not recompute them (see
markovchainCache).
Value
A numeric scalar in [0,1] containing the SLEM. For the
trivial one-state chain, 0 is returned.
References
Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times, 2nd edition. American Mathematical Society.
See Also
spectralGap, impliedTimescales,
is.irreducible, period
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
slem(mc)
Spectral gap of a Markov chain
Description
Computes the spectral gap of a finite, irreducible discrete-time Markov chain, a lightweight diagnostic of its convergence and mixing behaviour.
Usage
spectralGap(object)
## S4 method for signature 'markovchain'
spectralGap(object)
Arguments
object |
A |
Details
The spectral gap is defined from the second largest eigenvalue modulus
(SLEM, see slem) as
\mathrm{gap} = 1 - \mathrm{SLEM}.
As with slem, only irreducibility is required. A periodic
chain has SLEM = 1 and therefore spectral gap 0: this is
the mathematically correct value, not an error condition, since a
periodic chain never contracts towards its stationary distribution.
A larger spectral gap indicates faster convergence to stationarity; see
impliedTimescales for the timescale associated with each
non-trivial eigenvalue individually, of which the SLEM gives the slowest
(dominant) one.
Value
A numeric scalar in [0,1] containing the spectral gap. For
the trivial one-state chain, 1 is returned.
References
Levin, D. A. and Peres, Y. (2017). Markov Chains and Mixing Times, 2nd edition. American Mathematical Society.
See Also
slem, impliedTimescales,
is.irreducible
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
spectralGap(mc)
States of a Markov chain
Description
Returns the names of the states of a Markov chain, in the order of its transition matrix.
Usage
states(object)
## S4 method for signature 'markovchain'
states(object)
Arguments
object |
A |
Value
A character vector, the states slot.
Author(s)
Giorgio Spedicato
See Also
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames=list(statesNames,statesNames)),
name = "A markovchain Object"
)
states(markovB)
names(markovB)
Statistical tests for Markov chains
Description
Tests of hypotheses on observed sequences of states, based on transition counts (Anderson and Goodman 1957; Kullback, Kupperman and Ku 1962):
-
verifyMarkovProperty(): the first-order Markov property, i.e. that the next state is independent of the previous one given the present one (against a second-order chain); -
assessOrder(): the same hypothesis with the Pearson statistic, also for a list of independent sequences; -
verifyEmpiricalToTheoretical(): that the sequence (or a matrix of transition counts) comes from a given chain; -
verifyHomogeneity(): that several sequences (or count matrices) share the same transition matrix; -
assessStationarity(): that the transition probabilities do not change over time, comparingnblocksconsecutive blocks of the sequence.
Usage
verifyMarkovProperty(
sequence,
method = c("G", "Pearson", "simulation"),
B = 9999,
seed = NULL,
verbose = TRUE
)
assessOrder(sequence, verbose = TRUE)
verifyEmpiricalToTheoretical(
data,
object,
method = c("G", "Pearson", "simulation"),
B = 9999,
seed = NULL,
verbose = TRUE
)
verifyHomogeneity(
inputList,
method = c("G", "Pearson", "simulation"),
B = 9999,
seed = NULL,
verbose = TRUE
)
assessStationarity(sequence, nblocks, structural.zeros = NULL, verbose = TRUE)
Arguments
sequence |
An observed sequence of states (a vector); for
|
method |
The statistic: |
B |
Number of Monte Carlo samples for |
seed |
Optional random seed for |
verbose |
Logical: print the result? |
data |
An observed sequence of states, or a matrix of transition counts with the states as dimnames. |
object |
A |
inputList |
A list of at least two observed sequences or matrices of transition counts (with the states as dimnames). |
nblocks |
Number of consecutive blocks of (nearly) equal length into which the sequence is split, at least two. |
structural.zeros |
Optional logical matrix, with one row and column
per state (in the order of |
Details
Each test compares observed transition counts with the counts
expected under the null hypothesis, by the likelihood-ratio statistic
G^2 = 2 \sum O \log(O / E) (method = "G") or by Pearson's
X^2 = \sum (O - E)^2 / E (method = "Pearson"); cells with no
expected count are left out, and the degrees of freedom count only the
transitions actually observed. The p-value is from the chi-squared
distribution, or, with method = "simulation", from B samples
simulated under the null hypothesis (the G^2 statistic, p-value
(1 + \#\{simulated \ge observed\}) / (B + 1)), which is more
reliable when many counts are small. Sequences of numbers or factors are
compared as character strings.
Value
An object of class "htest", printed if verbose = TRUE and
returned invisibly, with the usual components statistic, parameter
(degrees of freedom), p.value, method and data.name, and also
dof. Depending on the test it also contains the observed and
expected counts and the estimated transitionMatrix
(verifyMarkovProperty(), verifyEmpiricalToTheoretical()), the
pooled counts and the transitionCounts of each element
(verifyHomogeneity()), and, with method = "simulation", the
simulated statistics (simulations) and B.
References
Anderson, T. W. and Goodman, L. A. (1957). Statistical inference about Markov chains. The Annals of Mathematical Statistics 28(1), 89-110.
Kullback, S., Kupperman, M. and Ku, H. H. (1962). Tests for contingency tables and Markov chains. Technometrics 4(4), 573-608.
See Also
assessIndependence() (independence of consecutive states),
selectOrder() (order by information criteria), compareChains().
Examples
data(rain, package = "markovchain")
# first-order Markov property of the Alofi rainfall sequence
verifyMarkovProperty(rain$rain)
assessOrder(rain$rain)
# compatibility with a chain: the fitted one, and a different one
fit <- markovchainFit(rain$rain)$estimate
verifyEmpiricalToTheoretical(rain$rain, fit)
s <- c("0", "1-5", "6+")
uniform <- new("markovchain", states = s,
transitionMatrix = matrix(1 / 3, 3, 3, dimnames = list(s, s)))
verifyEmpiricalToTheoretical(rain$rain, uniform)
# the first and second half of the sequence have the same transitions
verifyHomogeneity(list(rain$rain[1:548], rain$rain[549:1096]))
# time-homogeneity over four blocks
assessStationarity(rain$rain, nblocks = 4)
# a Monte Carlo p-value
verifyMarkovProperty(rain$rain, method = "simulation", B = 499, seed = 1)
Stationary distributions of a Markov chain
Description
Returns the stationary distributions of a Markov chain: the
probability vectors \pi with \pi P = \pi. There is one for
each recurrent class; every stationary distribution is a convex
combination of them.
Usage
steadyStates(object)
Arguments
object |
A |
Value
A matrix with one stationary distribution per row (per column if
the chain is stored by columns, byrow = FALSE), with the states as
column (row) names.
Note
The steady states are identified starting from which eigenvectors correspond to identity eigenvalues and then normalizing them to sum up to unity. When negative values are found in the matrix, the eigenvalues extraction is performed on the recurrent classes submatrix.
Author(s)
Giorgio Spedicato
See Also
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames=list(statesNames,statesNames)),
name = "A markovchain Object"
)
steadyStates(markovB)
Restrict a Markov chain to a subset of states
Description
Restricts a markovchain object to a chosen subset of its states,
either as a raw (generally non-stochastic) principal submatrix, or as a
properly renormalized Markov chain describing behaviour conditional on
staying inside the subset.
Usage
subchain(object, states, method = c("submatrix", "renormalize"))
## S4 method for signature 'markovchain'
subchain(object, states, method = c("submatrix", "renormalize"))
Arguments
object |
A |
states |
A character vector of at least one state name from
|
method |
Either |
Details
The two methods are deliberately named after two different, standard constructions, so that the choice – and its consequences – is explicit rather than implied:
"submatrix"Simply the entries of
Pwith both indices restricted tostates, with no adjustment. Its rows generally sum to less than one, because probability mass that originally went to states outside the subset is dropped, not redistributed. This is the "Q" block used, e.g., when building the fundamental matrix of an absorbing chain (seefundamentalMatrix): a useful building block for other computations, but not itself a transition matrix of any Markov chain, which is why it is returned as a plain matrix."renormalize"Each retained row is divided by its own sum, so the result is row-stochastic and can be wrapped in a
markovchainobject. This is the chain of successive positions ofobject, conditioned on the event that it never leavesstates(sometimes called the chain "watched on"states, or its taboo probabilities; see Norris (1997), Section 3.3). It requires every state instatesto have strictly positive probability of transitioning within the subset (otherwise that conditioning event has probability zero from that state, and the row cannot be renormalized); an error is raised naming any state that fails this, rather than silently producing a row ofNaN.
Neither method requires object to be irreducible: restricting to
a subset of states is meaningful for any chain, and is often used
precisely to study one communicating class in isolation.
The implementation performs no eigendecomposition; it is
O(k^2) time and memory for a subset of size k, after an
O(n^2) extraction from the full n-state matrix.
Value
If method = "submatrix": a plain numeric matrix (not a
markovchain object, since its rows generally do not sum to one),
the principal submatrix of the transition matrix restricted to
states, always returned in row-stochastic orientation regardless
of object's own storage convention.
If method = "renormalize": a new markovchain object on
exactly the states in states, row-stochastic, describing the
chain conditional on never leaving that subset.
References
Norris, J. R. (1998). Markov Chains. Cambridge University Press.
See Also
lazyChain, fundamentalMatrix,
canonicForm
Examples
statesNames <- c("a", "b", "c")
mc <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.5, 0.3, 0.2,
0.2, 0.6, 0.2,
0.1, 0.1, 0.8), byrow = TRUE, nrow = 3,
dimnames = list(statesNames, statesNames)))
# Raw submatrix: rows no longer sum to 1, mass has "leaked" to "c".
subchain(mc, c("a", "b"), method = "submatrix")
rowSums(subchain(mc, c("a", "b"), method = "submatrix"))
# Renormalized: a genuine markovchain, conditional on staying in {a, b}.
watched <- subchain(mc, c("a", "b"), method = "renormalize")
watched
rowSums(watched@transitionMatrix)
Discretize an AR(1) process into a Markov chain (Tauchen's method)
Description
Approximates the stationary first-order autoregressive process
y_t = (1-\rho)\alpha + \rho y_{t-1} + \varepsilon_t, \qquad
\varepsilon_t \overset{\mathrm{iid}}{\sim} \mathcal N(0,\sigma^2)
by a finite-state Markov chain on an evenly spaced grid, following Tauchen (1986).
Usage
tauchen(alpha, sigma, rho, size, k = 3)
Arguments
alpha |
A single finite number: the unconditional mean of the process. |
sigma |
A single finite positive number: the standard deviation of
the innovation |
rho |
A single number in |
size |
A single integer of at least |
k |
A single positive number, the half-width of the grid in units
of the process's unconditional standard deviation
|
Details
The grid is n=\code{size} evenly spaced points
y_1<\cdots<y_n spanning
[\alpha-k\sigma_y,\ \alpha+k\sigma_y], with half-spacing
w=(y_n-y_1)/(2(n-1)). Writing \Phi for the standard normal
CDF, the transition probabilities from grid point y_i are
P_{i1} = \Phi\!\left(\frac{y_1-(1-\rho)\alpha-\rho y_i+w}{\sigma}\right),
P_{in} = 1-\Phi\!\left(\frac{y_n-(1-\rho)\alpha-\rho y_i-w}{\sigma}\right),
P_{ij} = \Phi\!\left(\frac{y_j-(1-\rho)\alpha-\rho y_i+w}{\sigma}\right) -
\Phi\!\left(\frac{y_j-(1-\rho)\alpha-\rho y_i-w}{\sigma}\right),
\quad 1<j<n,
i.e. the probability that y_t (a normal draw centred at the AR(1)
conditional mean) lands in the half-open bin around y_j, with the
two end bins extended to \pm\infty so that rows sum to exactly
1.
Tauchen's method is simple and fast (O(n^2) normal CDF
evaluations) but the grid width is fixed by k regardless of
size: for a coarse grid (small size) it under-resolves the
bulk of the distribution, and for rho close to \pm1 the true
unconditional variance is large and sensitive to k. See
rouwenhorst for an alternative that tends to match the
persistence of near-unit-root processes more accurately and needs no
arbitrary grid-width parameter.
Value
A named list with two elements:
chainThe discretized
markovchainobject, with state names equal to the grid values ofyformatted to 4 significant digits.statesThe numeric grid of
y-values themselves, in the same order aschain's states. Returning the actual levels alongside the chain, rather than only generic state labels"1","2", ..., is deliberate: the whole point of discretizing an AR(1) process is usually to do further numeric work with the levels (e.g. plugging them into a pricing formula), and re-deriving the grid fromalpha,sigma,rhoandka second time by hand is both extra work and a place for an off-by-one or rounding mismatch to creep in.
References
Tauchen, G. (1986). Finite state markov-chain approximations to univariate and vector autoregressions. Economics Letters, 20(2), 177-181.
See Also
Examples
out <- tauchen(alpha = 0, sigma = 1, rho = 0.9, size = 5)
out$states
out$chain
# The chain's own stationary variance should be close to the AR(1)'s
# theoretical unconditional variance sigma^2 / (1 - rho^2).
pi <- as.numeric(steadyStates(out$chain))
sum(pi * (out$states - sum(pi * out$states))^2)
1 / (1 - 0.9^2)
Discretize an AR(1) process into a Markov chain (Tauchen-Hussey method)
Description
Approximates the stationary first-order autoregressive process
y_t = (1-\rho)\alpha + \rho y_{t-1} + \varepsilon_t, \qquad
\varepsilon_t \overset{\mathrm{iid}}{\sim} \mathcal N(0,\sigma^2)
by a finite-state Markov chain on Gauss-Hermite nodes, following Tauchen and Hussey (1991), with the choice of the standard deviation of the nodes proposed by Floden (2008) as an option.
Usage
tauchenHussey(
alpha,
sigma,
rho,
size,
sigmaWeight = c("conditional", "floden", "unconditional")
)
Arguments
alpha |
A single finite number: the unconditional mean of the process. |
sigma |
A single finite positive number: the standard deviation of
the innovation |
rho |
A single number in |
size |
A single integer of at least |
sigmaWeight |
How the standard deviation |
Details
The nodes y_1, \ldots, y_n and probability weights
\omega_1, \ldots, \omega_n are those of the n-point
Gauss-Hermite rule for N(\alpha, \hat\sigma^2), and
P_{ij} \propto \omega_j \frac{\phi(y_j;\ (1-\rho)\alpha + \rho y_i,\
\sigma)}{\phi(y_j;\ \alpha,\ \hat\sigma)},
normalized by rows, with \phi(\cdot; m, s) the normal density. It
is fitFunction with the AR(1) transition density and
quadrature = "gauss-hermite".
The method is accurate for moderate persistence, but with
\hat\sigma = \sigma the nodes are too concentrated when \rho
is close to one and the chain understates the unconditional variance;
with \hat\sigma = \sigma_y it overstates the persistence and
understates the conditional variance. Floden (2008) shows that his
weighted choice is a good compromise; for very persistent processes
rouwenhorst is usually preferable (Kopecky and Suen 2010).
The vignette reproduces the conditional and unconditional standard
deviations of Floden's Table 1.
Value
A named list with two elements, chain and states,
in the same form as returned by tauchen.
References
Tauchen, G. and Hussey, R. (1991). Quadrature-based methods for obtaining approximate solutions to nonlinear asset pricing models. Econometrica, 59(2), 371-396. doi:10.2307/2938261
Floden, M. (2008). A note on the accuracy of Markov-chain approximations to highly persistent AR(1) processes. Economics Letters, 99(3), 516-520.
Kopecky, K. A. and Suen, R. M. H. (2010). Finite state Markov-chain approximations to highly persistent processes. Review of Economic Dynamics, 13(3), 701-714.
See Also
fitFunction, tauchen,
rouwenhorst
Examples
out <- tauchenHussey(alpha = 0, sigma = sqrt(0.03), rho = 0.95, size = 5,
sigmaWeight = "floden")
out$chain
# unconditional standard deviation of the chain (Floden 2008, Table 1: 0.4792)
pi <- as.numeric(steadyStates(out$chain))
sqrt(sum(pi * (out$states - sum(pi * out$states))^2))
Time correlations and time relaxations of observed sequences
Description
timeCorrelations computes the time autocorrelation of an observed
sequence of states, or the time cross-correlation of two sequences, at
stationarity. timeRelaxations computes how the expected value of
the observable defined by a sequence evolves from a given initial
distribution. They correspond to time_correlations() and
time_relaxations() of PyDTMC.
Usage
timeCorrelations(object, sequence1, sequence2 = NULL, timePoints = 1)
## S4 method for signature 'markovchain'
timeCorrelations(object, sequence1, sequence2 = NULL, timePoints = 1)
timeRelaxations(object, sequence, initial = NULL, timePoints = 1)
## S4 method for signature 'markovchain'
timeRelaxations(object, sequence, initial = NULL, timePoints = 1)
Arguments
object |
A |
sequence1, sequence |
A sequence of states of the chain (character vector or factor). |
sequence2 |
An optional second sequence of states. If |
timePoints |
A vector of non-negative whole numbers, the lags at which the quantities are computed. |
initial |
The initial distribution: |
Details
A sequence defines an observable f on the states: f_j is the
number of times state j occurs in it. With f from
sequence1, g from sequence2, transition matrix
P and stationary distribution \pi,
\mathrm{timeCorrelations}(t) = \sum_i \pi_i f_i (P^t g)_i =
E_\pi[f(X_0) g(X_t)],
and, with initial distribution \mu,
\mathrm{timeRelaxations}(t) = \mu P^t f = E_\mu[f(X_t)].
For an ergodic chain, both converge as t grows, to
E_\pi[f] E_\pi[g] and to E_\pi[f] respectively, at a speed
governed by the second largest eigenvalue modulus
(slem).
The powers of P are applied by repeated multiplication, and by
repeated squaring for long lags, never through an eigendecomposition.
PyDTMC 9.0.0 switches to an eigendecomposition as soon as a lag exceeds
the number of states; since its left and right eigenvectors are not
biorthonormal when P has complex eigenvalues, it then returns wrong
values at every lag for such chains (the tests of this function include
one, whose correct values were checked with numpy).
timeCorrelations needs a unique stationary distribution, i.e.
exactly one recurrent class, and stops otherwise (PyDTMC returns
None). timeRelaxations is defined for every chain; unlike
PyDTMC, it does not require a unique stationary distribution.
Value
A numeric vector with one value per element of
timePoints, named after them.
References
Noe, F., Doose, S., Daidone, I., Loellmann, M., Sauer, M., Chodera, J. D. and Smith, J. C. (2011). Dynamical fingerprints for probing individual relaxation processes in biomolecular dynamics with simulations and kinetic experiments. Proceedings of the National Academy of Sciences, 108(12), 4822-4827.
See Also
redistribute, slem,
relaxationTime
Examples
statesNames <- c("a", "b", "c")
mc <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.5, 0.5, 0, 0.2, 0.3, 0.5, 0.1, 0.1, 0.8),
byrow = TRUE, nrow = 3, dimnames = list(statesNames, statesNames)))
x <- c("a", "b", "c", "c", "c", "a")
timeCorrelations(mc, x, timePoints = 0:5)
timeRelaxations(mc, x, initial = "a", timePoints = c(0, 1, 10, 100))
Single Year Corporate Credit Rating Transititions
Description
Matrix of Standard and Poor's Global Corporate Rating Transition Frequencies 2000 (NR Removed)
Usage
data(tm_abs)
Format
An 8 x 8 numeric matrix of transition counts, with rows and columns named
after the rating classes "AAA", "AA", "A",
"BBB", "BB", "B", "C" and "D".
References
European Securities and Markets Authority, 2016 https://cerep.esma.europa.eu/cerep-web/statistics/transitionMatrice.xhtml
Examples
data(tm_abs)
Apply a boundary condition to a Markov chain's first and last state
Description
Replaces the transition rows of a markovchain object's first and
last state (in states(object) order) with an absorbing,
reflecting, or semi-reflecting rule, leaving every other row unchanged.
Usage
toBoundedChain(object, boundaryCondition)
## S4 method for signature 'markovchain'
toBoundedChain(object, boundaryCondition)
Arguments
object |
A |
boundaryCondition |
Either:
|
Details
This function assumes – as is standard for a boundary condition – that
states(object) is meaningfully ordered along a line, first state
to last state, as it would be e.g. for birthDeath or any
other chain built to represent a bounded random walk. It does not check
this (there is no general way to check it from the transition matrix
alone) and applies the same first/last-row replacement regardless of
object's actual structure; only the two boundary rows are ever
touched, so applying it to a chain whose states are not linearly ordered
simply reinterprets whichever states happen to be listed first and last.
Unlike gamblersRuin, which is absorbing at both ends by
construction and cannot be un-done, toBoundedChain() can be
applied to any existing chain and with any of the three conditions,
including reflecting or semi-reflecting ones that gamblersRuin()
does not offer directly.
The implementation touches only 2 of the n rows and is
O(n) time and memory beyond copying the transition matrix.
Value
A new markovchain object, row-stochastic, on the same
states as object, identical to object except in its
first and last transition rows.
See Also
Examples
bd <- birthDeath(p = c(0.3, 0.4, 0.5), q = c(0.2, 0.3, 0.1))
absorbed <- toBoundedChain(bd, "absorbing")
absorbed@transitionMatrix[1, ]
absorbed@transitionMatrix[4, ]
reflected <- toBoundedChain(bd, "reflecting")
reflected@transitionMatrix[1, ]
semiReflected <- toBoundedChain(bd, 0.25)
semiReflected@transitionMatrix[1, ]
Represent a Markov chain as a plain R list
Description
Converts a markovchain object to a plain, self-describing R list:
the same information toFile writes to disk, kept in memory.
fromDictionary reverses the conversion.
Usage
toDictionary(object)
## S4 method for signature 'markovchain'
toDictionary(object)
fromDictionary(d)
Arguments
object |
A |
d |
A list as returned by |
Details
Unlike PyDTMC's own to_dictionary()/from_dictionary(),
which represent a chain as a flat mapping from every
(from_state, to_state) pair to its probability – n^2
entries with no state grouping – this nests the representation by
source state, which is both more compact to read and directly
round-trips through R's own list-of-lists idiom without any special
tuple-key handling.
Value
A named list with four elements:
nameThe chain's
name, as a single string (possibly empty).statesA character vector of state names, in order.
byrowAlways
TRUE: the list always stores the chain row-stochastically, regardless ofobject's own storage convention, so that the representation is unambiguous without also having to interpret this flag.transitionMatrixA named list of named lists:
transitionMatrix[[i]][[j]]is the probability of moving from stateito statej. This is deliberately not a plain matrix, so that the structure serializes to JSON or YAML (viatoFile) as a self-describing object keyed by state name, rather than a bare array whose meaning depends on remembering a row/column order.
fromDictionary returns a markovchain object.
See Also
Examples
statesNames <- c("a", "b")
mc <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.4, 0.6), byrow = TRUE,
nrow = 2, dimnames = list(statesNames, statesNames)))
d <- toDictionary(mc)
d$transitionMatrix$a$b # 0.3: probability of moving from "a" to "b"
identical(fromDictionary(d)@transitionMatrix, mc@transitionMatrix)
Export the transition graph as Graphviz DOT or Mermaid text
Description
toDot writes the transition graph of a Markov chain in the DOT
language of Graphviz; toMermaid writes it as a Mermaid flowchart.
The states are the nodes and every transition with positive probability
is an edge labelled with its probability.
Usage
toDot(object, file = NULL, digits = 3, minProbability = 0, direction = "LR")
## S4 method for signature 'markovchain'
toDot(object, file = NULL, digits = 3, minProbability = 0, direction = "LR")
toMermaid(
object,
file = NULL,
digits = 3,
minProbability = 0,
direction = "LR"
)
## S4 method for signature 'markovchain'
toMermaid(
object,
file = NULL,
digits = 3,
minProbability = 0,
direction = "LR"
)
Arguments
object |
A |
file |
An optional file path. If given, the text is also written there (UTF-8) and returned invisibly. |
digits |
The number of significant digits of the probabilities shown on the edges. |
minProbability |
Transitions with probability not above this value are left out; the default, 0, keeps every possible transition. |
direction |
The layout direction: |
Details
The edges follow the outgoing distribution of each state whatever the
storage of the transition matrix (byrow), so a chain and its
column-stochastic copy give the same text. State names are quoted and
escaped, so they may contain spaces, quotes or other punctuation. In the
Mermaid output the nodes get the identifiers s1, s2, ...,
with the state names as labels, because Mermaid identifiers cannot
contain arbitrary characters.
The DOT text can be rendered with Graphviz (for instance
dot -Tpng chain.dot -o chain.png) or with
DiagrammeR::grViz(); the Mermaid text can be pasted into any
Markdown renderer that supports Mermaid diagrams, or rendered with
DiagrammeR::mermaid().
Value
The text, as a single character string (invisibly when
file is given).
See Also
toFile, plot,markovchain,missing-method
Examples
statesNames <- c("a", "b", "c")
mc <- new("markovchain", states = statesNames, name = "Example",
transitionMatrix = matrix(c(0.5, 0.5, 0, 0.2, 0.3, 0.5, 0, 0, 1),
byrow = TRUE, nrow = 3, dimnames = list(statesNames, statesNames)))
cat(toDot(mc), "\n")
cat(toMermaid(mc, direction = "TB"), "\n")
Write or read a Markov chain to or from a file
Description
Writes a markovchain object to a JSON, YAML, CSV or XML file, or reads
one back, using the same representation as toDictionary.
Usage
toFile(object, file, format = NULL)
## S4 method for signature 'markovchain'
toFile(object, file, format = NULL)
fromFile(file, format = NULL)
Arguments
object |
A |
file |
A single file path to write to or read from. If |
format |
One of |
Details
The JSON and YAML formats store exactly what toDictionary
returns (name, state names, and the transition probabilities nested by
source state), and round-trip a chain exactly, including full numeric
precision (toFile writes both JSON and YAML with 17 significant
digits, enough to recover every double exactly).
The CSV format only stores the transition matrix itself, as a table of
probabilities with the state names as both the header row and the first
column – there is no natural place in a CSV file for the chain's
name, so it is not preserved by toFile(..., format = "csv")
and fromFile always returns an unnamed chain for a .csv
file. This is the same limitation PyDTMC's own CSV format has.
The XML format is the one of PyDTMC, so files can be exchanged with it in
both directions: a root element MarkovChain with one Item
element per transition, whose attributes are state_from,
state_to and probability. All n^2 transitions are
written, zeros included, and probabilities use 17 significant digits, so
the round trip is exact. The name of the chain is stored as an
attribute of the root element, which PyDTMC ignores when reading. When
reading, the states are taken in the order in which their self
transitions (state_from equal to state_to) appear, as
PyDTMC does, and the name is restored if the attribute is present.
Writing XML uses only base R; reading it requires the xml2
package.
Writing JSON requires the jsonlite package, and writing YAML
requires the yaml package; both are only in Suggests, and an
informative error is raised if the relevant package is not installed.
Reading has the same requirements for the format being read. CSV uses
only base R and has no extra package dependency.
Value
toFile returns file, invisibly. fromFile
returns a markovchain object.
See Also
Examples
## Not run:
statesNames <- c("a", "b")
mc <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.4, 0.6), byrow = TRUE,
nrow = 2, dimnames = list(statesNames, statesNames)))
toFile(mc, "chain.json")
identical(fromFile("chain.json")@transitionMatrix, mc@transitionMatrix)
## End(Not run)
Return the n-step transition chain
Description
Returns the markovchain object whose transition matrix is
P^{\code{order}}: from any state, its one-step transition
probabilities are the original chain's order-step transition
probabilities.
Usage
toNthOrder(object, order)
Arguments
object |
A |
order |
A single integer of at least |
Details
This is a thin, discoverability-only wrapper around
object ^ order (see ^,markovchain,numeric-method),
provided under this name because PyDTMC's equivalent method is
called to_nth_order(). It exists so that the operation is easy to
find by that name; it introduces no new computation; the underlying
^ method is already O(n^3\log(\code{order})) via repeated
squaring (expm::%^%), not a naive order-fold
product, so there is nothing to improve on algorithmically here.
Value
A new markovchain object on the same states as
object, with transition matrix P^{\code{order}}.
See Also
Examples
mc <- new("markovchain", states = c("a", "b"),
transitionMatrix = matrix(c(0.9, 0.1, 0.3, 0.7), byrow = TRUE, nrow = 2))
identical(unclass(toNthOrder(mc, 5)@transitionMatrix), unclass((mc ^ 5)@transitionMatrix))
Topological entropy of a Markov chain
Description
Computes the topological entropy of the graph of a discrete-time Markov chain: the exponential growth rate of the number of distinct admissible paths, ignoring their probabilities.
Usage
topologicalEntropy(object, base = 2)
## S4 method for signature 'markovchain'
topologicalEntropy(object, base = 2)
Arguments
object |
A |
base |
A finite numeric scalar strictly greater than one. The default,
|
Details
If A is the 0/1 adjacency matrix with A_{ij}=1 exactly when
p_{ij}>0, the topological entropy is
h_{top} = \log_b \rho(A),
where \rho(A) is the spectral radius (Perron root) of A.
Only the pattern of positive entries matters: the value depends on which
transitions are possible, not on how likely they are. It is the upper
bound of the entropy rate over all the Markov chains sharing that graph
(the variational principle, see Parry, 1964), so
entropyRate(object) <= topologicalEntropy(object) for an
irreducible chain. The bound is attained by the maximal-entropy
(Parry) chain on the same graph, and also, for instance, by a chain whose
every row is uniform over a common number of successors. A chain that is a
single cycle (deterministic dynamics) has topologicalEntropy = 0.
No irreducibility is needed: for a reducible chain the result is the
largest value over its communicating classes. A probability that is
positive but numerically tiny counts as a transition, exactly as in
is.irreducible.
The cost is one eigenvalue computation, O(n^3) time and
O(n^2) memory for a dense chain. It mirrors PyDTMC's
topological_entropy, which uses the natural logarithm.
Value
A non-negative numeric scalar in units determined by base.
References
Parry, W. (1964). Intrinsic Markov chains. Transactions of the American Mathematical Society, 112, 55-66.
Cover, T. M. and Thomas, J. A. (2006). Elements of Information Theory, 2nd edition. Wiley.
See Also
entropyRate, normalizedEntropyRate
Examples
statesNames <- c("a", "b")
mc <- new("markovchain",
states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.1, 0.9),
byrow = TRUE, nrow = 2,
dimnames = list(statesNames, statesNames)))
topologicalEntropy(mc)
Generator matrix from a transition matrix
Description
Computes the generator Q of a continuous time Markov
chain whose transition matrix over a period of length t is P, as the
matrix logarithm Q = \log(P) / t, so that
\exp(t Q) = P.
Usage
transition2Generator(P, t = 1, method = "logarithm")
Arguments
P |
A transition matrix (rows summing to one) over a period of length
|
t |
Length of the period, a positive number. |
method |
Method used: only |
Details
Not every transition matrix is the transition matrix of a
continuous time chain (the embedding problem): the matrix returned is a
valid generator only if its off-diagonal entries are non-negative, which
is not checked. freq2Generator() gives regularized estimates that are
always valid generators.
Value
A square matrix with the dimensions of P, the generator
\log(P) / t.
See Also
Other continuous time Markov chains:
ExpectedTime(),
ctmcFit(),
freq2Generator(),
generatorToTransitionMatrix(),
impreciseProbabilityatT(),
is.CTMCirreducible(),
is.TimeReversible(),
probabilityatT(),
rctmc()
Examples
P <- matrix(c(0.4, 0.6, 0.1, 0.9), nrow = 2, byrow = TRUE)
Q <- transition2Generator(P)
Q
expm::expm(Q) # gives back P
Transition probability between two states
Description
Returns the one-step probability of moving from state t0 to
state t1.
Usage
transitionProbability(object, t0, t1)
## S4 method for signature 'markovchain'
transitionProbability(object, t0, t1)
Arguments
object |
A |
t0 |
Name of the current state. |
t1 |
Name of the next state. |
Value
A number, the transition probability.
Author(s)
Giorgio Spedicato
See Also
conditionalDistribution() for the whole distribution of the
next state.
Examples
statesNames <- c("a", "b", "c")
markovB <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 1, 0, 0.1, 0.8, 0.1), nrow = 3,
byrow = TRUE, dimnames=list(statesNames,statesNames)),
name = "A markovchain Object"
)
transitionProbability(markovB,"b", "c")
Build an Ehrenfest urn model Markov chain
Description
Constructs the Ehrenfest diffusion model: balls balls are split
between two urns, A and B; at each step, one of the balls balls is
chosen uniformly at random and moved to the other urn. The chain tracks
the number of balls in urn A.
Usage
urnModel(balls, states = NULL)
Arguments
balls |
A single positive integer, the total number of balls. The
chain has |
states |
An optional character vector of |
Details
The Ehrenfest model is the classical example of a chain whose
equilibrium behaviour matches thermodynamic intuition despite every
individual transition being fully reversible: its stationary
distribution is \mathrm{Binomial}(\code{balls}, 1/2) (each ball is,
at equilibrium, independently in urn A or B with probability 1/2),
sharply concentrated around \code{balls}/2 for large
balls even though the chain only ever moves one ball at a time
and is reflecting, not absorbing, at the boundaries. It is irreducible
and reversible for every balls, but periodic with period 2
(the parity of the ball count in urn A alternates every step): pass the
result through lazyChain first if an aperiodic chain is
needed, e.g. for mixingTime.
Value
A new, row-stochastic markovchain object with
balls + 1 states. From state i (0<i<\code{balls}),
P_{i,i-1} = i/\code{balls}, \qquad P_{i,i+1} = 1 - i/\code{balls},
the probability that the ball moved was one of the i currently in
urn A (decreasing A's count) versus one of the \code{balls}-i
currently in urn B (increasing it). States 0 and balls
(all balls in one urn) are reflecting: the next ball moved must
come from the only non-empty urn, so P_{0,1}=P_{\code{balls},
\code{balls}-1}=1 exactly.
References
Ehrenfest, P. and Ehrenfest, T. (1907). Uber zwei bekannte Einwande gegen das Boltzmannsche H-Theorem. Physikalische Zeitschrift, 8, 311-314.
See Also
Examples
ehrenfest <- urnModel(balls = 4)
ehrenfest
steadyStates(ehrenfest) # approximately Binomial(4, 0.5): 1/16 6/16 ...
dbinom(0:4, 4, 0.5)
Matrix to create zeros
Description
Matrix to create zeros
Usage
zeros(n)
Arguments
n |
size of the matrix |
Value
a square matrix of zeros