Module contents
Lesson 2 of 31Core 100 min

Markov chains I: transitions, state classification and first-step analysis

A discrete-time Markov chain is determined by an initial distribution and a transition matrix. Derive Chapman-Kolmogorov and the strong Markov property, classify states into recurrent or transient communicating classes, and solve hitting probabilities and expected hitting times using first-step analysis and the fundamental matrix of absorbing chains.

After this lesson you can

  • Build the transition matrix of a system described in words and calculate its distribution at step n.
  • Classify finite-chain states into communicating, recurrent and transient classes using a graph algorithm.
  • Set up and solve absorption probabilities and expected hitting times through first-step analysis.
  • Use the fundamental matrix to find the expected number of visits and its variance.
  • Prove the recurrence criterion Σ P^n_ii = ∞ and apply it to a random walk on Z^d using Pólya's theorem.

Before you start

A state that summarizes what matters

A server request can be waiting, executing or finished. If knowing the current state is enough to calculate the distribution of the next one, we need not retain the entire history to predict one step. The same holds for gambler’s ruin if the current capital and probability of winning each bet contain all relevant information. In an n-gram model, the state must include the necessary context, not just the last symbol when prediction depends on several previous ones.

Choose transitions in the figure. Follow the probability mass rather than an individual path: the mass represents the distribution of many possible realizations. Change a connection and observe whether a class can lose mass to the outside.

InteractiveBuild a chain and follow its mass
A100.0 %B0.0 %C0.0 %D0.0 %
  • Outline color: communicating class
  • Arrow thickness: mass leaving at the next step

Each node’s interior area represents its current probability. Faint arrows indicate possible transitions with zero flow.

Edge weights: source row, destination column

Row and column order: A, B, C, D. A zero weight removes the edge.

Matrix P after normalizing each row
0.500.500.000.000.500.500.000.000.000.000.500.500.000.000.500.50
step 0
Class {A, B}closed, recurrent
Class {C, D}closed, recurrent
Total mass1.0000
Modify transitions and advance the distribution. Colors show communicating classes and the tool identifies which are closed. A non-closed class of a finite chain is transient.

The Markov property and the row transition matrix

The row corresponds to the current state and the column to the next one. By the chain rule, a path i0,…,ini_0,\ldots,i_n has probability μ0(i0)∏k=0n−1Pikik+1\mu_0(i_0)\prod_{k=0}^{n-1}P_{i_k i_{k+1}}. The row distribution evolves as μn+1=μnP\mu_{n+1}=\mu_nP, so μn=μ0Pn\mu_n=\mu_0P^n. If distributions are written as column vectors, the equivalent operation is P⊤μnP\T\vb{\mu}_n; choosing and consistently using one convention avoids an orientation error.

The property does not say that past and future are unconditionally independent: they share the current state. Nor does it guarantee that an arbitrarily chosen variable is a Markov state. For example, to detect the first appearance of HTH in coin tosses, we must retain the matching relevant prefix; knowing only that it has not appeared yet does not capture all predictive information.

Proof

Condition on the intermediate state Xm=kX_m=k. From kk, the Markov property and homogeneity make the probability of being in jj after another nn steps equal to PkjnP^n_{kj}. The law of total probability sums over kk. With P0=IP^0=I, this recurrence also identifies nn-step probabilities with entries of the matrix power.

∎

Stop and start again

The ordinary property concerns a fixed time. The strong Markov property extends the argument to a stopping time τ\tau: conditional on τ<∞\tau<\infty and state XτX_\tau, the subsequent process has the law of the chain started in that state and is conditionally independent of information up to τ\tau. It applies to the natural filtration, or another filtration with respect to which the chain satisfies the corresponding Markov property.

Proof

For an event AA known up to τ\tau, decompose A∩{τ<∞,Xτ=i}A\cap\{\tau<\infty,X_\tau=i\} into the disjoint union of A∩{τ=n,Xn=i}A\cap\{\tau=n,X_n=i\} for n≥0n\ge0. By the definition of information at a stopping time, each term belongs to Fn\mathcal F_n. For any finite future sequence, the Markov property at fixed time nn replaces its conditional probability with that of the same sequence started from ii. This probability depends on neither nn nor AA, so it factors out of the sum. This proves the claim on {τ<∞}\{\tau<\infty\}; no attempt is made to define XτX_\tau when τ=∞\tau=\infty.

∎

The stopping condition is essential: retrospectively choosing the last maximum of a path can reveal the future, as seen in the previous lesson.

Classes, return and the size of the state space

Write i→ji\to j if there exists n≥0n\ge0 with Pijn>0P^n_{ij}>0. Two states communicate if each is reachable from the other. The communicating classes are the strongly connected components of the graph with edges Pij>0P_{ij}>0. A class is closed if no edge leaves it; a chain is irreducible if it has one class. A closed class can have several states: it is not the same as one absorbing state.

Let Ti+=inf⁡{n≥1:Xn=i}T_i^+=\inf\{n\ge1:X_n=i\} and fii=Pi(Ti+<∞)f_{ii}=\Pr_i(T_i^+<\infty). A state is recurrent if fii=1f_{ii}=1 and transient if fii<1f_{ii}<1. A recurrent state is positive recurrent if EiTi+<∞\E_iT_i^+<\infty and null recurrent if that expectation is infinite. Recurrence is a class property. In a finite chain every closed class is recurrent and every non-closed class transient; in infinite spaces, closure does not suffice to guarantee recurrence.

To justify the series criterion, count visits to ii including the initial visit. After each return, strong Markov restarts the problem: the probability of completing at least rr returns is fiirf_{ii}^r. By the expectation formula for a nonnegative integer-valued variable, the expected number of visits is ∑r≥0fiir\sum_{r\ge0} f_{ii}^r. On the other hand, summing visit indicators and using monotone convergence gives ∑n≥0Piin\sum_{n\ge0}P^n_{ii}. Hence,

∑n≥0Piin=11−fiisi fii<1,∑n≥0Piin=∞si fii=1.\sum_{n\ge0}P^n_{ii}=\frac1{1-f_{ii}}\quad\text{si }f_{ii}<1, \qquad \sum_{n\ge0}P^n_{ii}=\infty\quad\text{si }f_{ii}=1.

To see why recurrence propagates, if i→ji\to j and j→ij\to i, there are times r,sr,s with Pjir>0P^r_{ji}>0 and Pijs>0P^s_{ij}>0. Then Pjjr+n+s≥PjirPiinPijsP^{r+n+s}_{jj}\ge P^r_{ji}P^n_{ii}P^s_{ij}. If the return series of ii diverges, that of jj also diverges; swap the two states for the converse. In a finite closed class, the chain never leaves and at least one state is visited infinitely often on every path. If all were transient, the total number of visits to each would be finite almost surely, a contradiction. The class property makes them all recurrent. From any ii in a non-closed class there is a simple positive-probability path that exits before returning to ii. Once outside, returning to the class is impossible: otherwise the outside state would communicate with it. Therefore Pi(Ti+=∞)>0\Pr_i(T_i^+=\infty)>0 and ii is transient.

For the symmetric walk on Zd\Z^d, each step chooses one of the 2d2d neighbors with equal probability. Pólya’s theorem says it is recurrent in dimensions 1 and 2 and transient from dimension 3 onward. Odd-time returns are impossible by parity. To understand the scale at even times, Fourier inversion of the characteristic function φ(θ)=d−1∑j=1dcos⁡θj\varphi(\theta)=d^{-1}\sum_{j=1}^d\cos\theta_j gives

P0(X2n=0)=1(2π)d∫[−π,π]dφ(θ)2n  ⁣dθ.\Pr_0(X_{2n}=0)=\frac{1}{(2\pi)^d}\int_{[-\pi,\pi]^d}\varphi(\theta)^{2n}\,\dd\theta.

On the torus, ∣φ∣=1|\varphi|=1 only at the origin and the point with all coordinates π\pi. Near both, ∣φ∣=1−Θ(∥θ∥2)|\varphi|=1-\Theta(\|\theta\|^2) in local coordinates; integrating its power gives upper and lower bounds proportional to n−d/2n^{-d/2} through the change of variables u=n θu=\sqrt n\,\theta. Outside those neighborhoods the contribution decays exponentially. Thus P0(X2n=0)≍n−d/2\Pr_0(X_{2n}=0)\asymp n^{-d/2}, and the preceding criterion reduces the result to divergence of ∑n−d/2\sum n^{-d/2} for d≤2d\le2 and convergence for d≥3d\ge3.

InteractiveReturn in one, two and three dimensions

Selected path: coordinates versus time. A return occurs only when all are zero simultaneously.

  • Coordinate 1
  • Coordinate 2

Exact sum of return probabilities up to each step, including the initial visit:

  • 1D
  • 2D
  • 3D

At step 200, the sums are 11.326, 2.535, 1.470 for 1D, 2D, and 3D. Each count uses 120 independent walks per dimension. “No return” means only through the observed horizon: those walks may return later. Finite simulation does not establish limiting behavior.

200
Individual path
1
Returns of displayed path6
1D: no return by the horizon6/120 (5.0 %)
2D: no return by the horizon41/120 (34.2 %)
3D: no return by the horizon85/120 (70.8 %)
Compare reproducible paths and partial sums of return probabilities. Not returning before the horizon does not mean never returning: in particular, the censored fraction is not an exact measure of permanent escape.

First step: equations and boundary conditions

First-step analysis conditions on the first transition. For a target set AA, hi=Pi(TA<∞)h_i=\Pr_i(T_A<\infty) satisfies hi=1h_i=1 on AA and hi=∑jPijhjh_i=\sum_jP_{ij}h_j outside AA. In infinite spaces these equations may have several nonnegative solutions: the hitting probability is the smallest. Indeed, probabilities hi(n)=Pi(TA≤n)h_i^{(n)}=\Pr_i(T_A\le n) increase toward hih_i, and iteration starting from 11 on AA and 00 outside stays below every nonnegative solution with the same boundary values.

The expectation ti=EiTAt_i=\E_iT_A satisfies ti=0t_i=0 on AA and ti=1+∑jPijtjt_i=1+\sum_jP_{ij}t_j outside, allowing infinity. A finite solution to a system written without checking absorption conditions may not be the desired expectation.

In gambler’s ruin, the states are 0,1,…,N0,1,\ldots,N, with absorbing endpoints and pp of moving up, q=1−pq=1-p of moving down. The probability hkh_k of reaching NN before 00 satisfies h0=0h_0=0, hN=1h_N=1 and hk=phk+1+qhk−1h_k=ph_{k+1}+qh_{k-1}. Solving the recurrence gives hk=k/Nh_k=k/N if p=q=1/2p=q=1/2; if 0<p<10<p<1 and p≠qp\ne q,

hk=1−(q/p)k1−(q/p)N.h_k=\frac{1-(q/p)^k}{1-(q/p)^N}.

The probability of ruin is 1−hk1-h_k: absorption at one endpoint occurs almost surely in this finite system. The powers approach one another as pp approaches 1/21/2 and the direct formula can lose numerical accuracy; the limit is the straight line.

InteractiveRuin: from first step to solution
  • Probability of reaching N
  • Fair coin: k / N
Initial capital 3
↙ Lose with 52.00 %
Capital 2
Reach N afterward: 14.16 %
↘ Win with 48.00 %
Capital 4
Reach N afterward: 30.77 %
Contributions to success: 7.36 % + 14.77 % ≈ 22.13 %.

Each bet changes capital by one and 0 and N are absorbing. The curve is calculated exactly from first-step equations, not by simulation.

48 %
10
3
First step
Reach N before 022.13 %
Ruin before reaching N77.87 %
Fair-coin reference30.00 %
Change initial capital, target and probability of winning. Compare the local first-step equation with the probability of reaching the target for all capital values.

Fundamental matrix

In a finite absorbing chain, order transient states first and absorbing states afterward, and suppose some absorbing state is reachable from every transient state. Then P=[QR0I]P=\begin{bmatrix}Q&R\\0&I\end{bmatrix} and

N=(I−Q)−1=∑n≥0Qn,B=NR,t=N1.N=(I-Q)^{-1}=\sum_{n\ge0}Q^n,\quad B=NR,\quad \vb t=N\vb 1.

The entry NijN_{ij} is the expected number of visits to jj before absorption, including the initial visit if i=ji=j; BiaB_{ia} is the probability of absorption at aa. The series equals the inverse because, in a finite chain where absorption is reachable from every transient state, there is a common number of steps and a uniform positive probability of absorption within that time: transient mass decays geometrically in blocks.

If VjV_j counts visits to jj, its second moment is obtained by summing indicators and ordered pairs of times. The first term is NijN_{ij}; after a visit to jj, the expected number of strictly later visits is Njj−1N_{jj}-1. Therefore EiVj2=Nij(2Njj−1)\E_iV_j^2=N_{ij}(2N_{jj}-1) and

Var⁡i(Vj)=Nij(2Njj−1)−Nij2.\Var_i(V_j)=N_{ij}(2N_{jj}-1)-N_{ij}^2.

Do not apply the inverse to a classification that left a closed class without absorption inside QQ: then I−QI-Q is singular. In code, solve linear systems without forming the inverse merely to multiply it by a vector when the full matrix is unnecessary.

Lab: a small chain library

First construct the strongly connected components using Tarjan’s algorithm. The discovery index and the lowest index reachable by edges that remain on the stack let us extract a class when its root closes. Then check each class for outgoing edges. The following procedure is for finite matrices; a positive entry, however small, defines an edge in the model.

[ ]Communicating classes with Tarjan's algorithmBrowser
import numpy as np

def clases_markov(P):
    P = np.asarray(P, dtype=float)
    n = len(P)
    if P.shape != (n, n) or not np.all(np.isfinite(P)) or np.any(P < 0) or not np.allclose(P.sum(axis=1), 1):
        raise ValueError('P debe ser una matriz estocástica por filas')
    indice = [-1] * n
    bajo = [0] * n
    pila, en_pila, clases = [], [False] * n, []
    contador = 0

    def visitar(v):
        nonlocal contador
        indice[v] = bajo[v] = contador
        contador += 1
        pila.append(v)
        en_pila[v] = True
        for w in np.flatnonzero(P[v] > 0):
            w = int(w)
            if indice[w] < 0:
                visitar(w)
                bajo[v] = min(bajo[v], bajo[w])
            elif en_pila[w]:
                bajo[v] = min(bajo[v], indice[w])
        if bajo[v] == indice[v]:
            clase = []
            while True:
                w = pila.pop()
                en_pila[w] = False
                clase.append(w)
                if w == v:
                    break
            clases.append(sorted(clase))

    for v in range(n):
        if indice[v] < 0:
            visitar(v)
    clases.sort(key=lambda c: c[0])
    resultado = []
    for clase in clases:
        fuera = [j for j in range(n) if j not in clase]
        cerrada = not np.any(P[np.ix_(clase, fuera)] > 0)
        resultado.append((clase, cerrada))
    return resultado

P = np.array([[0.5, 0.5, 0, 0], [0.2, 0.3, 0.5, 0],
              [0, 0, 0, 1], [0, 0, 1, 0]])
print('clases y cerradas:', clases_markov(P))
mu0 = np.array([1., 0, 0, 0])
print('ley en el paso 4:', np.round(mu0 @ np.linalg.matrix_power(P, 4), 6))

The final class is closed but neither of its two states is absorbing. The distribution is calculated with matrix_power, which uses repeated squaring; for long horizons compare the result with suitable propagation or structure and monitor rounding error. To simulate, sample a different row according to each path’s state.

[ ]Simulate a row-stochastic matrixBrowser
def simular_cadena(P, inicial, pasos, cantidad, rng):
    P = np.asarray(P, dtype=float)
    acumulada = P.cumsum(axis=1)
    acumulada[:, -1] = 1.0  # elimina el redondeo en el extremo
    trayectorias = np.empty((cantidad, pasos + 1), dtype=int)
    trayectorias[:, 0] = inicial
    for t in range(pasos):
        actual = trayectorias[:, t]
        u = rng.random(cantidad)
        trayectorias[:, t + 1] = (u[:, None] >= acumulada[actual]).sum(axis=1)
    return trayectorias

rng = np.random.default_rng(26021)
muestra = simular_cadena(P, 0, 4, 20_000, rng)
print('ley simulada en el paso 4:', np.round(np.bincount(muestra[:, -1], minlength=4) / len(muestra), 6))
print('ley por matrices:', np.round(mu0 @ np.linalg.matrix_power(P, 4), 6))

The comparison uses the same matrix validated in the preceding cell; simular_cadena assumes its rows are valid distributions. The inverse-transform intervals are half-open; the final column is set to one so rounding does not produce a nonexistent state.

[ ]Ruin: equations versus simulationBrowser
def matriz_ruina(N, p):
    P = np.zeros((N + 1, N + 1))
    P[0, 0] = P[N, N] = 1
    for k in range(1, N):
        P[k, k + 1], P[k, k - 1] = p, 1 - p
    return P

def absorcion(P, transitorios, absorbentes):
    Q = P[np.ix_(transitorios, transitorios)]
    R = P[np.ix_(transitorios, absorbentes)]
    A = np.eye(len(transitorios)) - Q
    fundamental = np.linalg.solve(A, np.eye(len(transitorios)))
    return fundamental, np.linalg.solve(A, R), np.linalg.solve(A, np.ones(len(transitorios)))

P_ruina = matriz_ruina(10, 0.48)
F, B, duracion = absorcion(P_ruina, list(range(1, 10)), [0, 10])
print('probabilidad de ruina desde 3:', round(B[2, 0], 8))
print('duración esperada desde 3:', round(duracion[2], 6))
print('visitas esperadas a 3 y su varianza:', round(F[2, 2], 6),
      round(F[2, 2] * (2 * F[2, 2] - 1) - F[2, 2]**2, 6))

rng = np.random.default_rng(2602)
M = 20_000
capital = np.full(M, 3, dtype=np.int16)
pasos = np.zeros(M, dtype=np.int32)
activos = (capital > 0) & (capital < 10)
while activos.any():
    ix = np.flatnonzero(activos)
    capital[ix] += np.where(rng.random(len(ix)) < 0.48, 1, -1)
    pasos[ix] += 1
    activos = (capital > 0) & (capital < 10)
print('ruina simulada:', round(np.mean(capital == 0), 5))
print('duración simulada:', round(pasos.mean(), 4))

The Monte Carlo comparison has random error. Paths are generated until absorption and are not discarded for exceeding a time limit; this is feasible in this small example, while larger models benefit from a limit and explicit reporting of censoring. The linear system is the exact reference for the model, apart from rounding error.

Lab: waiting for a pattern

The state is the length of the longest observed suffix matching a prefix of the pattern. After adding a coin outcome, retain the longest valid suffix; if the entire pattern matches, absorb. This automaton remembers exactly the information needed for the next step. For example, after HT and another H, HTH is complete, whereas after HT and T the useful suffix is empty.

[ ]Prefix automaton and waiting timeBrowser
def transicion_patron(patron, estado, cara):
    candidato = patron[:estado] + cara
    for longitud in range(min(len(patron), len(candidato)), -1, -1):
        if longitud == 0 or candidato.endswith(patron[:longitud]):
            return longitud

def matriz_patron(patron):
    if not patron or any(c not in 'HT' for c in patron):
        raise ValueError('patrón no vacío de H y T')
    L = len(patron)
    P = np.zeros((L + 1, L + 1))
    for i in range(L):
        for cara in 'HT':
            P[i, transicion_patron(patron, i, cara)] += 0.5
    P[L, L] = 1
    return P

def espera_patron(patron):
    P = matriz_patron(patron)
    L = len(patron)
    return np.linalg.solve(np.eye(L) - P[:L, :L], np.ones(L))[0]

def por_solapamientos(patron):
    return sum(2**k for k in range(1, len(patron) + 1)
               if patron[:k] == patron[-k:])

for patron in ['HTH', 'HHH', 'HTT']:
    print(patron, 'sistema:', espera_patron(patron),
          'solapamientos:', por_solapamientos(patron))

The sum of powers is the overlap formula for a fair coin: add 2k2^k for each prefix of length kk that is also a suffix, including the complete pattern. The automaton and system solution allow it to be checked in concrete examples; the formula does not transfer unchanged to a biased coin.

One proof uses fair bets. Before each toss a player enters with one unit and successively bets on the pattern’s letters: a correct bet doubles their capital and an incorrect one loses it. At the first appearance, TT players have entered. Those retaining capital are exactly those who started at a suffix matching a prefix of the pattern, and their total capital is the sum of 2k2^k over those overlaps. Expected net profit is zero because every bet is fair, so expected final capital is ET\E T. To justify taking the limit, first stop at T∧nT\wedge n; ET<∞\E T<\infty because each disjoint block of length LL has positive probability of containing the full pattern, and simultaneous capital is bounded by a constant depending on LL. Dominated convergence completes the argument.

As a second check, simulate HTH with an update rule independent of the automaton, retaining the last three characters needed for this pattern.

[ ]Monte Carlo for HTHBrowser
rng = np.random.default_rng(2603)
M = 10_000
tiempos = np.zeros(M, dtype=int)
for i in range(M):
    sufijo = ''
    while sufijo != 'HTH':
        sufijo = (sufijo + ('H' if rng.random() < 0.5 else 'T'))[-3:]
        tiempos[i] += 1
print('espera simulada HTH:', round(tiempos.mean(), 4))
print('error estándar estimado:', round(tiempos.std(ddof=1) / np.sqrt(M), 4))
print('espera exacta:', espera_patron('HTH'))

Exercises

NumericReaching ruin
A gambler starts with capital 3, stops at 0 or 10 and gains one unit with probability 0.48. What is the probability of reaching 0 before 10?
NumericWaiting for HTH
A fair coin is tossed until HTH is first observed. What is the expected number of tosses?
QuizEdges and recurrence
In a finite chain, {0, 1} is a communicating class; state 1 can reach 2, and 2 cannot reach 0 or 1. Which statements are necessarily true?

More than one answer may be correct.

ProofRestarting at a random time
Prove: Prove the strong Markov property for a discrete homogeneous chain and a stopping time of its natural filtration.
0
Work on the event of finite stopping and fix the state where the chain stops.

Step 1 of 3. How do you decompose the stopping event?

ProofPropagating recurrence
Prove: If i and j communicate and i is recurrent, prove that j is recurrent too.
0
The recurrence criterion is equivalent to divergence of the return-probability series.

Step 1 of 5. What follows from communication?

CodeClassify finite states
Implement classify_states(P): given a finite row-stochastic matrix, return a list of tuples (clase, cerrada). Each class is a sorted list of indices, classes are sorted by their first index, and cerrada is a Boolean. In this finite chain, non-closed classes are transient.
import numpy as np

def classify_states(P):
  pass
Shift+Enter to run
Key idea

The row transition matrix describes one transition; its powers propagate distributions. Graph geometry determines the classes of a finite chain, and recurrence is recognized through the return series. First-step analysis converts hitting events and times into equations, and the fundamental matrix summarizes visits and absorption when the transience assumptions hold.