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.
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 has probability . The row distribution evolves as , so . If distributions are written as column vectors, the equivalent operation is ; 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 . From , the Markov property and homogeneity make the probability of being in after another steps equal to . The law of total probability sums over . With , this recurrence also identifies -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 : conditional on and state , the subsequent process has the law of the chain started in that state and is conditionally independent of information up to . It applies to the natural filtration, or another filtration with respect to which the chain satisfies the corresponding Markov property.
Proof
For an event known up to , decompose into the disjoint union of for . By the definition of information at a stopping time, each term belongs to . For any finite future sequence, the Markov property at fixed time replaces its conditional probability with that of the same sequence started from . This probability depends on neither nor , so it factors out of the sum. This proves the claim on ; no attempt is made to define when .
∎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 if there exists with . Two states communicate if each is reachable from the other. The communicating classes are the strongly connected components of the graph with edges . 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 and . A state is recurrent if and transient if . A recurrent state is positive recurrent if 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 including the initial visit. After each return, strong Markov restarts the problem: the probability of completing at least returns is . By the expectation formula for a nonnegative integer-valued variable, the expected number of visits is . On the other hand, summing visit indicators and using monotone convergence gives . Hence,
To see why recurrence propagates, if and , there are times with and . Then . If the return series of diverges, that of 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 in a non-closed class there is a simple positive-probability path that exits before returning to . Once outside, returning to the class is impossible: otherwise the outside state would communicate with it. Therefore and is transient.
For the symmetric walk on , each step chooses one of the 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 gives
On the torus, only at the origin and the point with all coordinates . Near both, in local coordinates; integrating its power gives upper and lower bounds proportional to through the change of variables . Outside those neighborhoods the contribution decays exponentially. Thus , and the preceding criterion reduces the result to divergence of for and convergence for .
First step: equations and boundary conditions
First-step analysis conditions on the first transition. For a target set , satisfies on and outside . In infinite spaces these equations may have several nonnegative solutions: the hitting probability is the smallest. Indeed, probabilities increase toward , and iteration starting from on and outside stays below every nonnegative solution with the same boundary values.
The expectation satisfies on and 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 , with absorbing endpoints and of moving up, of moving down. The probability of reaching before satisfies , and . Solving the recurrence gives if ; if and ,
The probability of ruin is : absorption at one endpoint occurs almost surely in this finite system. The powers approach one another as approaches and the direct formula can lose numerical accuracy; the limit is the straight line.
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 and
The entry is the expected number of visits to before absorption, including the initial visit if ; is the probability of absorption at . 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 counts visits to , its second moment is obtained by summing indicators and ordered pairs of times. The first term is ; after a visit to , the expected number of strictly later visits is . Therefore and
Do not apply the inverse to a classification that left a closed class without absorption inside : then 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.
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.
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.
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.
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 for each prefix of length 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, 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 over those overlaps. Expected net profit is zero because every bet is fair, so expected final capital is . To justify taking the limit, first stop at ; because each disjoint block of length has positive probability of containing the full pattern, and simultaneous capital is bounded by a constant depending on . 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.
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
More than one answer may be correct.
Step 1 of 3. How do you decompose the stopping event?
Step 1 of 5. What follows from communication?
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):
passThe 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.