Solving Markov chains in R: the stationary distribution

Week 2 — Markov chains in R

Quantitative biology and integrative omics

About this lecture

In Markov chains we built a transition matrix P for a DNA sequence. In these slides we answer: if you keep stepping the chain, where does it end up? The answer is the equilibrium nucleotide composition.

  • Build P in R and take powers (%*%; why P^n is wrong; the expm package).
  • Watch the state distribution \mathbf{x}_t converge no matter where it starts.
  • The stationary distribution \boldsymbol\pi: the distribution that does not change, \boldsymbol\pi P = \boldsymbol\pi.
  • Find \boldsymbol\pi two ways in R:
    • (a) power iteration — keep multiplying by P;
    • (b) eigenvector of P^\top for eigenvalue 1 (eigen), connecting back to Eigenvalues in R.

Recap: one step is \mathbf{x}_{t+1} = \mathbf{x}_t P

From Markov chains, with row vectors and rows of P summing to 1:

\mathbf{x}_{t+1} = \mathbf{x}_t P, \qquad \mathbf{x}_t = \mathbf{x}_0 P^t.

A toy DNA-flavoured chain over {A, C, G, T} (a CpG-like dip: G rarely follows C):

bases <- c("A","C","G","T")
P <- matrix(c(0.30, 0.20, 0.25, 0.25,
              0.25, 0.35, 0.05, 0.35,   # C -> G is rare
              0.25, 0.25, 0.25, 0.25,
              0.15, 0.30, 0.25, 0.30),
            nrow = 4, byrow = TRUE,
            dimnames = list(bases, bases))
rowSums(P)        # A 1  C 1  G 1  T 1   <- valid transition matrix

Taking powers: %*%, not ^

To advance several steps, multiply by P repeatedly. P^n is wrong — it squares each entry elementwise.

x0 <- c(1, 0, 0, 0)          # start: definitely A
x1 <- x0 %*% P               # one step
x2 <- x1 %*% P               # two steps
x2

P2 <- P %*% P                # the 2-step transition MATRIX
# P^2  would be ELEMENTWISE squaring -- NOT this!

A reusable matrix-power helper (repeated multiplication):

matpow <- function(M, n) {
  R <- diag(nrow(M))               # identity
  for (i in seq_len(n)) R <- R %*% M
  R
}
x0 %*% matpow(P, 10)               # distribution after 10 steps

A package shortcut: expm

Base R has no built-in matrix power. The expm package adds the %^% operator:

# install.packages("expm")
library(expm)
P %^% 10                      # P raised to the 10th power (matrix power)
x0 %*% (P %^% 10)             # distribution after 10 steps
  • %^% is genuine matrix power (it uses %*% internally, efficiently).
  • It is only for convenience — the loop on the previous slide does the same thing.

From any start, the chain reaches the same distribution

Step the chain from two different starts and print every few steps:

step_n <- function(x, P, n) { for (i in seq_len(n)) x <- x %*% P; drop(x) }

startA <- c(1, 0, 0, 0)      # start at A
startT <- c(0, 0, 0, 1)      # start at T
for (n in c(1, 2, 5, 10, 20)) {
  cat("n =", n, " from A:", round(step_n(startA, P, n), 3), "\n")
  cat("n =", n, " from T:", round(step_n(startT, P, n), 3), "\n")
}
# By n = 20 both rows are essentially identical:
# from A: 0.232 0.281 0.194 0.293
# from T: 0.232 0.281 0.194 0.293

The two starts forget where they began and settle on the same distribution.

Try it: watch walkers converge

The stationary distribution stays the same after a step

The limit \boldsymbol\pi is stationary: stepping it once leaves it unchanged.

\boxed{\ \boldsymbol\pi P = \boldsymbol\pi\ }, \qquad \text{with } \sum_k \pi_k = 1,\ \ \pi_k \ge 0.

  • It is a fixed point of “multiply by P”: once you reach it, you stay.
  • Biologically: the equilibrium nucleotide composition of the DNA model — the base frequencies you expect in a very long sequence generated by P.
  • For the cell model: the long-run fraction of cells in each state.

The stationary distribution is an eigenvector

Rewrite the stationarity condition. \boldsymbol\pi P = \boldsymbol\pi says \boldsymbol\pi is a left eigenvector of P with eigenvalue 1.

eigen in R computes right eigenvectors (M\mathbf{v} = \lambda\mathbf{v}). Transpose to convert left → right:

\boldsymbol\pi P = \boldsymbol\pi \ \Longleftrightarrow\ P^\top \boldsymbol\pi^\top = \boldsymbol\pi^\top.

So \boldsymbol\pi^\top is the right eigenvector of P^\top for eigenvalue 1.

  • Every stochastic matrix has 1 as its largest eigenvalue (Eigenvalues in R’s \lambda).
  • Power iteration (repeated \times P) is exactly the power method picking out this dominant eigenvector.

Finding \boldsymbol\pi (a) by power iteration

Just keep multiplying until the vector stops changing:

pi_power <- function(P, tol = 1e-12, max_iter = 1000) {
  x <- rep(1 / nrow(P), nrow(P))     # any valid start, e.g. uniform
  for (i in seq_len(max_iter)) {
    xn <- x %*% P
    if (max(abs(xn - x)) < tol) break
    x <- xn
  }
  drop(xn)
}

pi_hat <- pi_power(P)
round(pi_hat, 4)        # 0.2323 0.2811 0.1938 0.2928
sum(pi_hat)             # 1
pi_hat %*% P            # check: equals pi_hat (stationary!)

Fun fact: Google’s underlying algorithm for finding search results (PAGERANK) is actually just this algorithm! Imagine if you had known eigenvalues 20 years ago?

Finding \boldsymbol\pi (b) via eigen(t(P))

Use the eigen-decomposition (Eigenvalues in R) of the transpose, take the eigenvalue-1 vector, make it real, positive, and sum-to-1:

e <- eigen(t(P))
e$values                         # the first is 1 (up to rounding)

v <- Re(e$vectors[, 1])          # eigenvector for lambda = 1 (drop tiny Im part)
pi_eig <- v / sum(v)             # normalise to a probability distribution
round(pi_eig, 4)                 # 0.2323 0.2811 0.1938 0.2928  -- same as (a)!
  • t(P) because \boldsymbol\pi is a left eigenvector but eigen returns right ones.
  • Eigenvectors come out scaled arbitrarily (and possibly negative/complex) → take Re, then divide by the sum to normalise.

Two methods, same answer

Power iteration (a) Eigenvector (b)
Idea keep doing \mathbf{x}\leftarrow\mathbf{x}P solve \boldsymbol\pi P=\boldsymbol\pi exactly
R loop with %*% eigen(t(P))
Needs nothing extra Eigenvalues in R eigen-decomposition
Normalise already sums to 1 divide eigenvector by its sum
Intuition the chain “forgets” its start fixed point = \lambda=1 eigenvector
round(pi_hat, 6)        # 0.232342 0.281134 0.193773 0.292751
round(pi_eig, 6)        # 0.232342 0.281134 0.193773 0.292751

The stationary distribution is the long-run base mix

For our matrix, \boldsymbol\pi \approx (0.232,\ 0.281,\ 0.194,\ 0.293):

  • A long sequence generated by P would be about 23% A, 28% C, 19% G, 29% T.
  • G is the rarest base — a downstream consequence of the CpG dip we put in (p_{CG}=0.05).
  • This equilibrium is a property of the dynamics (P), not of the starting base.
# Sanity check by simulation: long sequence -> observed frequencies ~ pi
set.seed(1)
s <- character(50000); s[1] <- "A"
for (t in 2:50000) s[t] <- sample(bases, 1, prob = P[s[t-1], ])
round(prop.table(table(factor(s, levels = bases))), 3)   # close to pi

Some chains never settle on a single distribution

Convergence to a single \boldsymbol\pi regardless of start needs the chain to be:

  • irreducible — every state reachable from every other (the graph is connected), and
  • aperiodic — not locked into a fixed cycle.

Counterexamples:

  • P = \begin{pmatrix}0&1\\1&0\end{pmatrix} (periodic): a start at state 1 oscillates 1\to2\to1\to\dots and never settles, though \boldsymbol\pi=(0.5,0.5) still satisfies \boldsymbol\pi P=\boldsymbol\pi.
  • A chain with two disconnected groups of states has many stationary distributions.

Our DNA matrix has all entries positive → both conditions hold → unique \boldsymbol\pi.

Summary

Concept Key fact R
Step \mathbf{x}_{t+1}=\mathbf{x}_t P x %*% P
Power \mathbf{x}_t=\mathbf{x}_0 P^t (not P^t!) loop of %*%, or expm::%^%
Convergence \mathbf{x}_t \to \boldsymbol\pi, start-independent iterate until stable
Stationary \boldsymbol\pi P = \boldsymbol\pi, \sum\pi_k=1 fixed point
Eigen view \boldsymbol\pi^\top = right eigenvector of P^\top, \lambda=1 eigen(t(P)), then /sum
Biology equilibrium base composition matches long-run simulation

Optional, under Further reading (Hidden Markov models, Fitting HMMs in R): so far the state was observed. In a Hidden Markov Model the state is hidden (e.g. “CpG island” vs “background”) and we see only emitted symbols — built on exactly this transition machinery.