Continuous-time Markov chains
When state changes occur at random times, a chain is described by a rate matrix Q. Construct it from exponential holding times and a jump chain, derive the forward and backward Kolmogorov equations and their matrix-exponential solution, study equilibrium, and apply the results to birth-death processes and queues. Simulate exactly with Gillespie and uniformization.
After this lesson you can
- Construct a system's rate matrix for server failures and repairs, chemical reactions or queues and simulate it with Gillespie.
- Derive the Kolmogorov equations and solve them using a matrix exponential and uniformization.
- Calculate equilibrium for birth-death processes and M/M/1 and M/M/c queue metrics.
- Calculate expected absorption times in continuous-time chains by first-step analysis.
- Estimate a rate matrix by maximum likelihood from continuously observed paths.
Before you start
A different clock in each state
A server can fail or recover at random times; a molecule can degrade before the next reaction; a queue receives one request while another finishes service. In discrete time we chose the next state at each step. Now we also need the waiting-time distribution until that step.
In a reaction network, Gillespie directly simulates the next time and reaction type from their rates. Compare paths with the deterministic closure equation: a nonlinear reaction means that equation is generally not the exact equation for the stochastic mean.
Rates, holding times and the jump chain
On a finite space, the rate matrix or generator satisfies for and . For ,
Off-diagonal entries are rates, not probabilities: they can exceed one because their units are inverse time. Every row of sums to zero.
The holding-time and jump-chain construction takes . If , the holding time at is exponential with rate and the next state is chosen with probability . If , is absorbing and the holding time is infinite. For a finite state set, exit rates are bounded and the construction produces a non-explosive chain.
On a countable space this matters. A pure-birth process with rate starting at zero has independent holding times with means : their expectations sum to a finite value, so the sum of times is finite almost surely. Infinitely many jumps occur in finite time. Writing an infinite matrix alone does not establish a conservative chain.
Kolmogorov equations
Write . The backward and forward Kolmogorov equations for finite are
By Chapman-Kolmogorov, . Substituting , subtracting , dividing by and taking the limit gives the backward equation in the first equality and the forward equation in the second. Left multiplication conditions on the state just after starting; right multiplication conditions on the state just before ending. If is a row distribution, .
For a finite matrix the exponential is the unique solution of the linear system. Numerically, use a stable method such as scaling and squaring, available in scipy.linalg.expm, rather than blindly summing a Taylor series at large times. On infinite spaces, explosion and domains must be controlled before using these identities as if they were finite matrices.
Uniformization: virtual steps and a Poisson clock
Uniformization chooses and , defines and applies that matrix at ticks of a Poisson clock with rate . Because has rows summing to zero and the bound makes the diagonal nonnegative, is stochastic. Clock steps are virtual: they do not change the continuous-time state.
Conditioning on the number of ticks up to , which is Poisson with mean ,
The equality also follows from and the fact that commutes with . Truncating after terms leaves row mass equal to the tail : this mass controls truncation error. When is large, starting the recurrence with can underflow; rescale or use another implementation.
Equilibrium and how long states are occupied
A continuous-time stationary distribution satisfies and . For a finite irreducible chain it exists and is unique. If additionally for all pairs, detailed balance holds and the chain is reversible. As in discrete time, detailed balance implies global balance, but not every stationary distribution is reversible.
The jump chain counts visits, whereas counts time. If all exit rates are positive and the jump chain has stationary distribution , then
provided the sums are finite and distributions normalized. Each visit to lasts on average: a state with slow exits occupies more time even without more visits. Absorbing states need separate treatment because .
For expected time to reach an absorbing set, first-step analysis gives outside the set and zero on it. If every transient state in a finite chain reaches the boundary almost surely, this is equivalent to . A finite solution is not guaranteed without those assumptions.
Birth and death: queues
A birth-death process only changes from to at rate or from to at rate . If the rates are positive where appropriate, detailed balance gives
The formula defines a distribution only if the normalizing series is finite and the chain is well-defined without explosion. An M/M/1 queue has Poisson arrivals at rate and exponential service at rate . With , and the mean number in the system is . The mean number waiting, excluding service, is . By Little’s law in steady state, and , so and . Times have units; is a customer count, not a time.
For M/M/c, with identical servers of rate , define and . Then
Death rates are . If , the normalizing series diverges and these equilibrium formulas do not apply to the infinite queue.
Gillespie and path observation
The Gillespie algorithm for channels with propensities sums , draws an exponential wait with rate and chooses channel with probability . If , the state is absorbing. It is exact for the CTMC model with propensities constant between jumps; it does not approximate the clock with fixed steps. The next-reaction variant maintains per-channel clocks and updates them after each event, accounting for dependencies among propensities.
In the next-reaction method of Gibson and Bruck, retain the proposed time for each channel and execute the earliest. After reaction, only propensities affected by the state change need updating. For a channel that did not fire and whose rate changes from to at , its proposed time becomes : this preserves the remaining internal hazard. A disabled channel moves to infinite time; one activated from zero rate needs an appropriate clock, and the channel that just fired needs a new threshold. A priority queue and dependency graph avoid updating unchanged channels; the actual advantage depends on system structure.
If a path is continuously observed until , let count jumps from to and be total time in , including the final holding time censored at . The log-likelihood conditional on the start is
For , the maximum-likelihood solution is ; if was never visited, its rates are unidentified. Observing only at fixed intervals gives transitions of : several jumps can be hidden between observations. Counting them as direct jumps with holding time generally biases the estimator.
Lab: uniformization and parallel simulation
First implement the uniformization series for a finite generator. Leave tail mass unnormalized: each row sum of the truncated matrix is minus the Poisson tail. The function checks that the clock parameter does not cause initial underflow; it does not claim to be a general implementation for arbitrarily large .
import numpy as np
from scipy.linalg import expm
from scipy.stats import poisson
def uniformizar(Q, t, tol=1e-12):
Q = np.asarray(Q, dtype=float)
if t < 0 or tol <= 0 or tol >= 1 or Q.ndim != 2 or Q.shape[0] != Q.shape[1]:
raise ValueError('parámetros inválidos')
off = Q.copy()
np.fill_diagonal(off, 0)
if np.any(off < 0) or not np.allclose(Q.sum(axis=1), 0):
raise ValueError('Q debe ser generador por filas')
Lambda = max(-np.diag(Q))
if Lambda == 0:
return np.eye(len(Q)), 0., 0
m = Lambda*t
if m > 500:
raise ValueError('reescala el problema: la recurrencia inicial puede subdesbordar')
P = np.eye(len(Q)) + Q/Lambda
potencia = np.eye(len(Q))
peso = np.exp(-m)
total = peso*potencia
k = 0
while poisson.sf(k, m) > tol:
k += 1
potencia = potencia @ P
peso *= m/k
total += peso*potencia
return total, float(poisson.sf(k, m)), k
Q = np.array([[-.4, .3, .1], [.2, -.5, .3], [.1, .4, -.5]])
P_u, cola, K = uniformizar(Q, 8.)
P_e = expm(8*Q)
print('truncación K, cola Poisson:', K, cola)
print('máximo error por fila L1:', np.max(np.abs(P_u-P_e).sum(axis=1)))
print('sumas de fila truncadas:', np.round(P_u.sum(axis=1), 12))The matrix discrepancy does not exceed the tail, apart from floating-point error, because every omitted term is nonnegative and has row sum equal to its weight. The check compares with expm, not another sum of the same series.
Now simulate many replications in parallel. Each advances its own clock; if its next jump falls after , it keeps its state until the end. The destination index comes from the rate row excluding the diagonal. Absorbing states are removed from the active set.
def finales_ctmc(Q, x0, T, replicas, rng):
Q = np.asarray(Q, float)
estados = np.full(replicas, x0, dtype=int)
tiempos = np.zeros(replicas)
activos = np.ones(replicas, dtype=bool)
tasas = Q.copy()
np.fill_diagonal(tasas, 0.)
salida = tasas.sum(axis=1)
while activos.any():
ids = np.flatnonzero(activos)
q = salida[estados[ids]]
absorbidos = ids[q == 0]
activos[absorbidos] = False
ids, q = ids[q > 0], q[q > 0]
if len(ids) == 0:
continue
siguiente = tiempos[ids] + rng.exponential(1/q)
terminan = siguiente > T
activos[ids[terminan]] = False
ids, q, siguiente = ids[~terminan], q[~terminan], siguiente[~terminan]
if len(ids):
distribucion = tasas[estados[ids]]/q[:, None]
acumulada = np.cumsum(distribucion, axis=1)
acumulada[:, -1] = 1.
destino = (rng.random(len(ids))[:, None] >= acumulada).sum(axis=1)
estados[ids] = destino
tiempos[ids] = siguiente
return estados
rng = np.random.default_rng(26081)
finales = finales_ctmc(Q, 0, 8., 20000, rng)
empirica = np.bincount(finales.astype(np.int32), minlength=3)/len(finales)
print('ley empírica:', np.round(empirica, 5))
print('ley por expm:', np.round(expm(8*Q)[0], 5))Consider two independent servers, each with failure rate and repair rate . State counts operational servers; failures occur at rate and independent simultaneous repairs at rate . Both down corresponds to . This is a different model from one shared repairer.
Q_servidores = np.zeros((3, 3))
for k in range(3):
if k > 0:
Q_servidores[k, k-1] = .1*k
if k < 2:
Q_servidores[k, k+1] = 2-k
Q_servidores[k, k] = -Q_servidores[k].sum()
A = Q_servidores.T.copy()
A[-1] = 1
pi_servidores = np.linalg.solve(A, np.array([0., 0., 1.]))
rng = np.random.default_rng(26082)
finales = finales_ctmc(Q_servidores, 2, 20., 20000, rng)
print('probabilidad estacionaria ambos caídos:', round(pi_servidores[0], 8), 'exacta:', 1/121)
print('frecuencia en t=20:', round(np.mean(finales == 0), 6))
print('ley exacta en t=20:', np.round(expm(20*Q_servidores)[2], 6))To measure time until both servers are down for the first time, stop the process on reaching and work only with transient states . The first-step system uses from the original matrix; it excludes repair after reaching the target.
Q_TT = Q_servidores[np.ix_([1, 2], [1, 2])]
tiempos_caida = np.linalg.solve(-Q_TT, np.ones(2))
print('tiempos esperados desde 1 y 2 servidores operativos:', tiempos_caida)
print('residuo del sistema:', np.round((-Q_TT) @ tiempos_caida - 1, 12))For M/M/2 with and per server, generate states without truncating the queue and compare final occupancy with the stationary distribution. An observation at the end of a path started empty is not an exact stationary sample; the comparison reports this simulation’s state at its particular horizon.
def finales_mm_c(lam, mu, c, T, replicas, rng):
x = np.zeros(replicas, dtype=int)
t = np.zeros(replicas)
activos = np.ones(replicas, dtype=bool)
while activos.any():
idx = np.flatnonzero(activos)
servicio = mu*np.minimum(x[idx], c)
total = lam + servicio
proximo = t[idx] + rng.exponential(1/total)
siguen = proximo <= T
activos[idx[~siguen]] = False
idx, servicio, total, proximo = idx[siguen], servicio[siguen], total[siguen], proximo[siguen]
if len(idx):
x[idx] += np.where(rng.random(len(idx))*total < lam, 1, -1)
t[idx] = proximo
return x
from math import factorial
lam, mu, c = 1.2, 1.5, 2
a, rho = lam/mu, lam/(c*mu)
pi0 = 1/(sum(a**n/factorial(n) for n in range(c)) + a**c/(factorial(c)*(1-rho)))from math import factorial
pi0 = 1/(sum(a**n/factorial(n) for n in range(c)) + a**c/(factorial(c)*(1-rho)))
def pi_mm_c(n):
return pi0*a**n/(factorial(n) if n < c else factorial(c)*c**(n-c))
rng = np.random.default_rng(26083)
ocupacion = finales_mm_c(lam, mu, c, 60., 10000, rng)
print('probabilidades empíricas de 0, 1 y 2 clientes:', [round(np.mean(ocupacion == n), 5) for n in range(3)])
print('probabilidades estacionarias:', [round(pi_mm_c(n), 5) for n in range(3)])
print('Lq teórica:', round((pi0*a**c/(factorial(c)*(1-rho)))*rho/(1-rho), 5))Lab: estimate Q from complete and discrete logs
Simulate complete paths of a three-state service. Store jump times and states as well as holding times and counts. Replications are independent: the bootstrap resamples paths rather than treating each jump within a path as an independent observation.
def log_ctmc(Q, x0, T, rng):
x, t = x0, 0.
tiempos, estados = [0.], [x]
S = np.zeros(len(Q))
N = np.zeros_like(Q, dtype=int)
while t < T:
tasa = -Q[x, x]
if tasa == 0:
S[x] += T-t
break
dt = rng.exponential(1/tasa)
if t+dt >= T:
S[x] += T-t
break
S[x] += dt
t += dt
pesos = Q[x].copy()
pesos[x] = 0
y = rng.choice(len(Q), p=pesos/tasa)
N[x, y] += 1
x = y
tiempos.append(t)
estados.append(x)
return np.array(tiempos), np.array(estados), S, N
def estimar_q(S, N):
S, N = np.asarray(S), np.asarray(N)
if np.any(S <= 0):
raise ValueError('una fila sin tiempo observado no es identificable')
Q = N/S[:, None]
np.fill_diagonal(Q, 0.)
np.fill_diagonal(Q, -Q.sum(axis=1))
return Q
Q_real = np.array([[-.3,.2,.1],[.4,-.6,.2],[.3,.2,-.5]])
rng = np.random.default_rng(26084)
logs = [log_ctmc(Q_real, 0, 20., rng) for _ in range(500)]
S = np.array([item[2] for item in logs])
N = np.array([item[3] for item in logs])
Q_hat = estimar_q(S.sum(axis=0), N.sum(axis=0))
print('Q verdadera:', Q_real)
print('Q estimada con logs completos:', np.round(Q_hat, 4))rng = np.random.default_rng(26085)
boot = []
for _ in range(300):
indices = rng.integers(0, len(logs), len(logs))
boot.append(estimar_q(S[indices].sum(axis=0), N[indices].sum(axis=0))[0, 1])
print('intervalo percentil bootstrap para q01:', np.round(np.quantile(boot, [.025, .975]), 4))
Delta = 1.
grid = np.arange(0, 20.+Delta, Delta)
S_panel = np.zeros(3)
N_panel = np.zeros((3,3), dtype=int)
for tiempos, estados, _, _ in logs:
observados = estados[np.searchsorted(tiempos, grid, side='right')-1]
for i, j in zip(observados[:-1], observados[1:]):
S_panel[i] += Delta
if i != j:
N_panel[i,j] += 1
Q_panel = estimar_q(S_panel, N_panel)
P_delta = expm(Delta*Q_real)
Q_naiva_limite = (P_delta-np.eye(3))/Delta
print('Q ingenua a partir de observaciones discretas:', np.round(Q_panel, 4))
print('límite de ese procedimiento (P(Δ)-I)/Δ:', np.round(Q_naiva_limite, 4))The printed limit is not for a fixed interval: some jumps and returns do not appear in the panel. The bootstrap interval quantifies variation between paths under this simulation procedure; it does not by itself correct discrete-observation bias.
Exercises
Step 1 of 3. How do you separate the first interval of duration h?
gillespie(Q_fn, x0, T, rng). Q_fn(x) returns a vector of nonnegative rates to each state, with zero at x. Simulate exponential waits and destinations until T, return the final state, and treat a row with zero total rate as absorbing.import numpy as np
def gillespie(Q_fn, x0, T, rng):
passThe generator combines rates and holding times. The matrix exponential and uniformization describe the same transitions; Gillespie simulates their jumps without discretizing the clock. Continuous-time equilibrium weights time, and complete logs allow estimation of rates that spaced observation can hide.