Daisuke Oyama
Faculty of Economics, University of Tokyo
Julia translation of the Python version, translated by Ryumei Nakada
This notebook demonstrates how to analyze finite-state Markov chains
with the MarkovChain class.
For basic concepts and properties on Markov chains, see
For algorithmic issues in detecting reducibility and periodicity of a Markov chain, see, for example,
from which we draw some examples below.
In [1]:
    
using Plots
using QuantEcon
using StatsBase
    
In [2]:
    
plotlyjs()
    
    
    Out[2]:
Define a custom pretty printing function:
In [3]:
    
prettyprint(arr) = Base.showarray(STDOUT, arr, false, header=false)
    
    Out[3]:
Consider the Markov chain given by the following stochastic matrix, taken from Exercise 3 in Jarvis and Shier (where the actual values of non-zero probabilities are not important):
In [4]:
    
P = zeros(6, 6)
P[1, 1] = 1
P[2, 5] = 1
P[3, 3], P[3, 4], P[3, 5] = 1/3, 1/3, 1/3
P[4, 1], P[4, 6] = 1/2, 1/2
P[5, 2], P[5, 5] = 1/2, 1/2
P[6, 1], P[6, 4] = 1/2, 1/2
P
    
    Out[4]:
Create a MarkovChain instance:
In [5]:
    
mc1 = MarkovChain(P)
    
    Out[5]:
This Markov chain is reducible:
In [6]:
    
is_irreducible(mc1)
    
    Out[6]:
In [7]:
    
length(communication_classes(mc1))
    
    Out[7]:
Determine the communication classes:
In [8]:
    
communication_classes(mc1)
    
    Out[8]:
Classify the states of this Markov chain:
In [9]:
    
recurrent_classes(mc1)
    
    Out[9]:
Obtain a list of the recurrent states:
In [10]:
    
recurrent_states = vcat(recurrent_classes(mc1)...)
    
    Out[10]:
Obtain a list of the transient states:
In [11]:
    
transient_states = setdiff(collect(1:n_states(mc1)), recurrent_states)
    
    Out[11]:
A Markov chain is reducible (i.e., its directed graph is not strongly connected) if and only if by symmetric permulations of rows and columns, its transition probability matrix is written in the form ("canonical form") $$ \begin{pmatrix} U & 0 \\ W & V \end{pmatrix}, $$ where $U$ and $W$ are square matrices.
Such a form for mc1 is obtained by the following:
In [12]:
    
permutation = vcat(recurrent_states, transient_states)
mc1.p[permutation, permutation]
    
    Out[12]:
This Markov chain is aperiodic (i.e., the least common multiple of the periods of the recurrent sub-chains is one):
In [13]:
    
is_aperiodic(mc1)
    
    Out[13]:
Indeed, each of the sub-chains corresponding to the recurrent classes has period $1$, i.e., every recurrent state is aperiodic:
In [14]:
    
for recurrent_class in recurrent_classes(mc1)
    sub_matrix = mc1.p[recurrent_class, recurrent_class]
    d = period(MarkovChain(sub_matrix))
    println("Period of the sub-chain")
    prettyprint(sub_matrix)
    println("\n = $d")
end
    
    
For each recurrent class $C$, there is a unique stationary distribution $\psi^C$
such that $\psi^C_i > 0$ for all $i \in C$ and $\psi^C_i = 0$ otherwise.
MarkovChain.stationary_distributions returns
these unique stationary distributions for the recurrent classes.
Any stationary distribution is written as a convex combination of these distributions.
In [15]:
    
stationary_distributions(mc1)
    
    Out[15]:
These are indeed stationary distributions:
In [16]:
    
stationary_distributions(mc1)[1]'* mc1.p
    
    Out[16]:
In [17]:
    
stationary_distributions(mc1)[2]'* mc1.p
    
    Out[17]:
Plot these distributions.
In [18]:
    
"""
Plot the given distribution.
"""
function draw_histogram(distribution;
        title="", xlabel="", ylabel="", ylim=(0, 1),
        show_legend=false, show_grid=false)
    
    n = length(distribution)
    p = bar(collect(1:n),
            distribution,
            xlim=(0.5, n+0.5),
            ylim=ylim,
            title=title,
            xlabel=xlabel,
            ylabel=ylabel,
            xticks=1:n,
            legend=show_legend,
            grid=show_grid)
    
    return p
end
    
    Out[18]:
Stationary distribution for the recurrent class:
In [19]:
    
titles = ["$recurrent_class"
          for recurrent_class in recurrent_classes(mc1)]
ps = []
for (title, dist) in zip(titles, stationary_distributions(mc1))
    push!(ps, draw_histogram(dist, title=title, xlabel="States"))
end
plot(ps..., layout=(1, 2))
    
    Out[19]:
Let us simulate our Markov chain mc1.
The simualte method generates a sample path
of length given by the first argument, ts_length,
with an initial state as specified by an optional argument init;
if not specified, the initial state is randomly drawn.
A sample path from state 1:
(Note: Transposing the output array here is just for visualization.)
In [20]:
    
simulate(mc1, 50, init=1)'
    
    Out[20]:
As is clear from the transition matrix P,
if it starts at state 1, the chain stays there forever,
i.e., 1 is an absorbing state, a state that constitutes a singleton recurrent class.
Start with state 2:
In [21]:
    
simulate(mc1, 50, init=2)'
    
    Out[21]:
You can observe that the chain stays in the recurrent class $\{2,5\}$
and visits states 2 and 5 with certain frequencies.
If init is not specified, the initial state is randomly chosen:
In [22]:
    
simulate(mc1, 50)'
    
    Out[22]:
Now, let us compute the frequency distribution along a sample path, given by $$ \frac{1}{t} \sum_{\tau=0}^{t-1} \mathbf{1}\{X_{\tau} = s\} \quad (s \in S). $$
In [23]:
    
"""
Return the distribution of visits by a sample path of length t
of mc with an initial state init.
"""
function time_series_dist(mc, ts::Array{Int}; init=rand(1:n_states(mc)))
    t_max = maximum(ts)
    ts_size = length(ts)
    
    X = simulate(mc, t_max, init=init)
    dists = Array{Float64}(n_states(mc), ts_size)
    bins = 1:n_states(mc)+1
    for (i, t) in enumerate(ts)
        h = fit(Histogram, X[1:t], bins, closed=:left)
        dists[:, i] = h.weights / t
    end
    
    return dists
end
function time_series_dist(mc, t::Int; init=rand(1:n_states(mc)))
    return time_series_dist(mc, [t], init=init)[:, 1]
end
    
    Out[23]:
Here is a frequency distribution along a sample path,  of length 100,
from initial state 2, which is a recurrent state:
In [24]:
    
time_series_dist(mc1, 100, init=2)
    
    Out[24]:
Length 10,000:
In [25]:
    
time_series_dist(mc1, 10^4, init=2)
    
    Out[25]:
The distribution becomes close to the stationary distribution (0, 1/3, 0, 0, 2/3, 0).
Plot the frequency distributions for a couple of different time lengths:
In [26]:
    
function plot_time_series_dists(mc, ts; init=rand(1:n_states(mc)), layout=(1,length(ts)))
    dists = time_series_dist(mc, ts, init=init)
    titles = ["t=$t" for t in ts]
    ps = []
    for (i, title) in enumerate(titles)
        p = draw_histogram(dists[:, i], title=title, xlabel="States")
        push!(ps, p)
    end
    plot(ps..., layout=layout)
end
    
    Out[26]:
In [27]:
    
init = 2
ts = [5, 10, 50, 100]
plot_time_series_dists(mc1, ts, init=init)
    
    Out[27]:
Start with state 3,
which is a transient state:
In [28]:
    
init = 3
ts = [5, 10, 50, 100]
plot_time_series_dists(mc1, ts, init=init)
    
    Out[28]:
Run the above cell several times; you will observe that the limit distribution differs across sample paths. Sometimes the state is absorbed into the recurrent class $\{1\}$, while other times it is absorbed into the recurrent class $\{2,5\}$.
Some sample path with init=3
In [29]:
    
init = 3
ts = [5, 10, 50, 100]
plot_time_series_dists(mc1, ts, init=init)
    
    Out[29]:
Another sample path with init=3
In [30]:
    
plot_time_series_dists(mc1, ts, init=init)
    
    Out[30]:
In fact, for almost every sample path of a finite Markov chain $\{X_t\}$, for some recurrent class $C$ we have $$ \frac{1}{t} \sum_{\tau=0}^{t-1} \mathbf{1}\{X_{\tau} = s\} \to \psi^C[s] \quad \text{as $t \to \infty$} $$ for all states $s$, where $\psi^C$ is the stationary distribution associated with the recurrent class $C$.
If the initial state $s_0$ is a recurrent state, then the recurrent class $C$ above is the one that contains $s_0$, while if it is a transient state, then the recurrent class to which the convergence occurs depends on the sample path.
Let us simulate with the remaining states, 4, 5, and 6.
Time series distributions for t=100
In [31]:
    
inits = [4, 5, 6]
t = 100
ps = []
for init in inits
    p = draw_histogram(
        time_series_dist(mc1, t, init=init),
        title="Initial state = $init",
        xlabel="States")
    push!(ps, p)
end
plot(ps..., layout=(1, 3))
    
    Out[31]:
Next, let us repeat the simulation for many times (say, 10,000 times)
and obtain the distribution of visits to each state at a given time period t.
That is, we want to simulate the marginal distribution at time t.
In [32]:
    
function QuantEcon.simulate(mc, ts_length, num_reps::Int=10^4; init=1)
    X = Array{Int}(ts_length, num_reps)
    for i in 1:num_reps
        X[:, i] = simulate(mc, ts_length, init=init)
    end
    return X
end
    
In [33]:
    
"""
Return the distribution of visits at time T by num_reps times of simulation
of mc with an initial state init.
"""
function cross_sectional_dist(mc, ts::Array{Int}, num_reps=10^4; init=rand(1:n_states(mc)))
    t_max = maximum(ts)
    ts_size = length(ts)
    dists = Array{Float64}(n_states(mc), ts_size)
    X = simulate(mc, t_max+1, num_reps, init=init)
    bins = 1:n_states(mc)+1
    for (i, t) in enumerate(ts)
        h = fit(Histogram, X[t, :], bins, closed=:left)
        dists[:, i] = h.weights / num_reps
    end
    return dists
end
function cross_sectional_dist(mc, t::Int, num_reps=10^4; init=rand(1:n_states(mc)))
    return cross_sectional_dist(mc, [t], num_reps, init=init)[:, 1]
end
    
    Out[33]:
Start with state 2:
In [34]:
    
init = 2
t = 10
cross_sectional_dist(mc1, t, init=init)
    
    Out[34]:
In [35]:
    
t = 100
cross_sectional_dist(mc1, t, init=init)
    
    Out[35]:
The distribution is close to the stationary distribution (0, 1/3, 0, 0, 2/3, 0).
Plot the simulated marginal distribution at t for some values of t.
In [36]:
    
function plot_cross_sectional_dists(mc, ts, num_reps=10^4; init=1)
    dists = cross_sectional_dist(mc, ts, num_reps, init=init)
    titles = map(t -> "t=$t", ts)
    ps = []
    for (i, title) in enumerate(titles)
        p = draw_histogram(dists[:, i], title=title, xlabel="States")
        push!(ps, p)
    end
    plot(ps..., layout=(1, length(ts)))
end
    
    Out[36]:
In [37]:
    
init = 2
ts = [2, 3, 5, 10]
plot_cross_sectional_dists(mc1, ts, init=init)
    
    Out[37]:
Starting with a transient state 3:
In [38]:
    
init = 3
t = 10
cross_sectional_dist(mc1, t, init=init)
    
    Out[38]:
In [39]:
    
t = 100
dist = cross_sectional_dist(mc1, t, init=init)
    
    Out[39]:
In [40]:
    
draw_histogram(dist,
               title="Cross sectional distribution at t=$t with init=$init",
               xlabel="States")
    
    Out[40]:
Observe that the distribution is close to a convex combination of
the stationary distributions (1, 0, 0, 0, 0, 0) and (0, 1/3, 0, 0, 2/3, 0),
which is a stationary distribution itself.
How the simulated marginal distribution evolves:
In [41]:
    
init = 3
ts = [2, 3, 5, 10]
plot_cross_sectional_dists(mc1, ts, init=init)
    
    Out[41]:
Since our Markov chain is aperiodic (i.e., every recurrent class is aperiodic), the marginal disribution at time $t$ converges as $t \to \infty$ to some stationary distribution, and the limit distribution depends on the initial state, according to the probabilities that the state is absorbed into the recurrent classes.
For initial states 4, 5, and 6:
In [42]:
    
inits = [4, 5, 6]
t = 10
ps = []
for init in inits
    p = draw_histogram(cross_sectional_dist(mc1, t, init=init),
                   title="Initial state = $init",
                   xlabel="States")
    push!(ps, p)
end
plot(ps..., layout=(1, length(inits)))
    
    Out[42]:
The marginal distributions at time $t$ are obtained by $P^t$.
In [43]:
    
ts = [10, 20, 30]
for t in ts
    P_t = mc1.p^t
    println("P^$t =")
    prettyprint(P_t)
    println()
end
    
    
In the canonical form:
In [44]:
    
Q = mc1.p[permutation, permutation]
println("Q =")
prettyprint(Q)
for t in ts
    Q_t = Q^t
    println("\nQ^$t =")
    prettyprint(Q_t)
end
    
    
Observe that the first three rows, which correspond to the recurrent states, are close to the stationary distributions associated with the corresponding recurrent classes.
Consider the Markov chain given by the following stochastic matrix, taken from Exercise 9 (see also Exercise 11) in Jarvis and Shier (where the actual values of non-zero probabilities are not important):
In [45]:
    
P = zeros(10, 10)
P[1, 4] = 1
P[2, [1, 5]] = 1/2
P[3, 7] = 1
P[4, [2, 3, 8]] = 1/3
P[5, 4] = 1
P[6, 5] = 1
P[7, 4] = 1
P[8, [7, 9]] = 1/2
P[9, 10] = 1
P[10, 6] = 1
P
    
    Out[45]:
In [46]:
    
mc2 = MarkovChain(P)
    
    Out[46]:
This Markov chain is irreducible:
In [47]:
    
is_irreducible(mc2)
    
    Out[47]:
This Markov chain is periodic:
In [48]:
    
is_aperiodic(mc2)
    
    Out[48]:
Its period, which we denote by $d$:
In [49]:
    
d = period(mc2)
    
    Out[49]:
Cyclic classes are:
Note: The function to identify the cyclic classes is only implemented in Python version and not available in Julia version. The result below is retrieved from the paper introduced above: Graph-Theoretic Analysis of Finite Markov Chains
In [50]:
    
cyclic_classes = [[1, 5, 7, 9], [4, 10], [2, 3, 6, 8]]
    
    Out[50]:
If a Markov chain is periodic with period $d \geq 2$, then its transition probability matrix is written in the form ("cyclic normal form") $$ \begin{pmatrix} 0 & P_1 & 0 & 0 & \cdots & 0 \\ 0 & 0 & P_2 & 0 & \cdots & 0 \\ 0 & 0 & 0 & P_3 & \cdots & 0 \\ \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & 0 & \cdots & P_{d-1} \\ P_d & 0 & 0 & 0 & \cdots & 0 \end{pmatrix}. $$
Represent our Markov chain in cyclic normal form:
In [51]:
    
permutation = vcat(cyclic_classes...)
Q = mc2.p[permutation, permutation]
    
    Out[51]:
Re-define the Markov chain with the above matrix Q:
In [52]:
    
mc2 = MarkovChain(Q)
    
    Out[52]:
Obtain the block components $P_1, \cdots, P_{d}$:
In [53]:
    
cyclic_classes = [[1, 2, 3, 4], [5, 6], [7, 8, 9, 10]]
    
    Out[53]:
In [54]:
    
P_blocks = []
for i in 1:d
    push!(P_blocks, mc2.p[cyclic_classes[(i-1)%d+1], :][:, cyclic_classes[i%d+1]])
    println("P_$i =")
    prettyprint(P_blocks[i])
    println()
end
    
    
$P^d$ is block diagonal:
In [55]:
    
P_power_d = mc2.p^d
prettyprint(P_power_d)
    
    
In [56]:
    
P_power_d_blocks = []
ordinals = ["1st", "2nd", "3rd"]
for (i, ordinal) in enumerate(ordinals)
    push!(P_power_d_blocks, P_power_d[cyclic_classes[i], :][:, cyclic_classes[i]])
    println("$ordinal diagonal block of P^d =")
    prettyprint(P_power_d_blocks[i])
    println()
end
    
    
The $i$th diagonal block of $P^d$ equals $P_i P_{i+1} \cdots P_d P_1 \cdots P_{i-1}$:
In [57]:
    
products = []
for i in 1:d
    R = P_blocks[i]
    string = "P_$i"
    for j in 1:d-1
        R = R * P_blocks[(i+j-1)%d+1]
        string *= " P_$((i+j-1)%d+1)"
    end
    push!(products, R)
    println(string, " =")
    prettyprint(R)
    println()
end
    
    
In [58]:
    
for (matrix0, matrix1) in zip(P_power_d_blocks, products)
    println(matrix0 == matrix1)
end
    
    
The Markov chain mc2 has a unique stationary distribution,
which we denote by $\psi$:
In [59]:
    
length(stationary_distributions(mc2))
    
    Out[59]:
In [60]:
    
psi = stationary_distributions(mc2)[1]
    
    Out[60]:
In [61]:
    
draw_histogram(psi,
               title="Stationary distribution",
               xlabel="States",
               ylim=(0, 0.35))
    
    Out[61]:
Obtain the stationary distributions $\psi^1, \ldots, \psi^{d}$ each associated with the diagonal blocks of $P^d$:
In [62]:
    
psi_s = []
for i in 1:d
    push!(psi_s, stationary_distributions(MarkovChain(P_power_d_blocks[i]))[1])
    println("psi^$i =")
    println(psi_s[i])
end
    
    
In [63]:
    
ps = []
for i in 1:d
    psi_i_full_dim = zeros(n_states(mc2))
    psi_i_full_dim[cyclic_classes[i]] = psi_s[i]
    p = draw_histogram(psi_i_full_dim,
                       title="ψ^$i",
                       xlabel="States")
    push!(ps, p)
end
plot(ps..., layout=(1, 3))
    
    Out[63]:
Verify that $\psi^{i+1} = \psi^i P_i$:
In [64]:
    
for i in 1:d
    println("psi^$i P_$i =")
    println(psi_s[i]' * P_blocks[i])
end
    
    
Verify that $\psi = (\psi^1 + \cdots + \psi^d)/d$:
In [65]:
    
# Right hand side of the above identity
rhs = zeros(n_states(mc2))
for i in 1:d
    rhs[cyclic_classes[i]] = psi_s[i]
end
rhs /= d
rhs
    
    Out[65]:
In [66]:
    
maximum(abs.(psi - rhs))
    
    Out[66]:
meaning right hand side is very close to $\psi$
Since the Markov chain in consideration is periodic, the marginal distribution does not converge, but changes periodically.
Let us compute the powers of the transition probability matrix (in cyclic normal form):
Print $P^1, P^2, \ldots, P^d$:
In [67]:
    
for i in 1:d+1
    println("P^$i =")
    prettyprint(mc2.p^i)
    println()
end
    
    
Print $P^{2d}$, $P^{4d}$, and $P^{6d}$:
In [68]:
    
for i in [k*d for k in [2, 4, 6]]
    println("P^$i =")
    prettyprint(mc2.p^i)
    println()
end
    
    
$P^{kd}$ converges as $k \to \infty$ to a matrix that contains $\psi^1, \ldots, \psi^d$.
Print $P^{kd+1}, \ldots, P^{kd+d}$ with $k = 10$ for example:
In [69]:
    
for i in 10*d+1:11*d
    println("P^$i =")
    prettyprint(mc2.p^i)
    println()
end
    
    
But $P^i$ itself does not converge.
Plot the frequency distribution of visits to the states
along a sample path starting at state 1:
In [70]:
    
init = 1
dist = time_series_dist(mc2, 10^4, init=init)
    
    Out[70]:
In [71]:
    
draw_histogram(dist,
               title="Time series distribution with init=$init",
               xlabel="States", ylim=(0, 0.35))
    
    Out[71]:
Observe that the distribution is close to the (unique) stationary distribution $\psi$.
In [72]:
    
psi
    
    Out[72]:
In [73]:
    
bar(psi, legend=false, xlabel="States", title="ψ")
    
    Out[73]:
Next, plot the simulated marginal distributions
at $T = 10d+1, \ldots, 11d, 11d+1, \ldots, 12d$ with initial state 1:
In [74]:
    
init = 1
k = 10
ts = [k*d + i + 1 for i in 1:2*d]
num_reps = 10^2
dists = cross_sectional_dist(mc2, ts, num_reps, init=init)
ps = []
for (i, t) in enumerate(ts)
    p = draw_histogram(dists[:, i],
                       title="t = $t")
    push!(ps, p)
end
plot(ps..., layout=(2, d))
    
    Out[74]:
Compare these with the rows of $P^{10d+1}, \ldots, P^{10d+d}$.
Consider the Markov chain given by the following stochastic matrix $P^{\varepsilon}$, parameterized by $\varepsilon$:
In [75]:
    
function P_epsilon(eps, p=0.5)
    P = [1-(p+eps) p         eps;
         p         1-(p+eps) eps;
         eps       eps       1-2*eps]
    return P
end
    
    Out[75]:
If $\varepsilon = 0$,
then the Markovh chain is reducible into two recurrent classes, [1, 2] and [3]:
In [76]:
    
P_epsilon(0)
    
    Out[76]:
In [77]:
    
recurrent_classes(MarkovChain(P_epsilon(0)))
    
    Out[77]:
If $\varepsilon > 0$ but small, the chain is irreducible,
but transition within each of the subsets [1, 2] and [3] is much more likely
than that between these sets.
In [78]:
    
P_epsilon(0.001)
    
    Out[78]:
In [79]:
    
recurrent_classes(MarkovChain(P_epsilon(0.001)))
    
    Out[79]:
Analytically, the unique stationary distribution of the chain with $\varepsilon > 0$
is (1/3, 1/3, 1/3), independent of the value of $\varepsilon$.
However, for such matrices with small values of $\varepsilon > 0$, general purpose eigenvalue solvers are numerically unstable.
For example, if we use Base.LinAlg.eig
to compute the eigenvector that corresponds
to the dominant (i.e., largest in magnitude) eigenvalue:
In [80]:
    
epsilons = [10.0^(-i) for i in 11:17]
for eps in epsilons
    println("epsilon = $eps")
    
    w, v = eig(P_epsilon(eps)')
    i = indmax(w)
    println(v[:, i]/sum(v[:, i]))
end
    
    
The same applies to Base.LinAlg.eigs:
In [81]:
    
epsilons = [10.0^(-i) for i in 11:17]
for eps in epsilons
    println("epsilon = $eps")
    
    w, v = eigs(P_epsilon(eps)', nev=2)
    i = indmax(w)
    println(v[:, i]/sum(v[:, i]))
end
    
    
The output becomes farther from the actual stationary distribution (1/3, 1/3, 1/3)
as $\varepsilon$ becomes smaller.
MarkovChain in quantecon employs
the algorithm called the "GTH algorithm",
which is a numerically stable variant of Gaussian elimination,
specialized for Markov chains.
In [82]:
    
epsilons = [10.0^(-i) for i in 12:17]
push!(epsilons, 1e-100)
for eps in epsilons
    println("epsilon = $eps")
    println(stationary_distributions(MarkovChain(P_epsilon(eps)))[1])
end
    
    
It succeeds in obtaining the correct stationary distribution for any value of $\varepsilon$.