Module contents
Lesson 8 of 31Core 110 min

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.

InteractiveReactions and paths

For state x, production, degradation and dimerization propensities are k₀, k₁x and k₂x(x−1)/2. An exponential wait with rate equal to their sum is drawn, then a reaction according to its propensity. If the sum is zero, the state remains fixed.

Molecule count versus time. Showing 12 paths from 120 replicates:

  • Individual paths
  • Replicate mean
  • Approximate deterministic closure

The exact mean satisfies m′ = k₀ − k₁m − k₂ E[X(X−1)]. The dashed curve numerically solves m′ = k₀ − k₁m − k₂m², approximating E[X(X−1)] by m²: this is a closure, not the exact mean with dimerization. The empirical mean uses all complete replicates and fluctuates with the sample.

With k₀ = 0, zero is absorbing. If k₀ > 0, reaching zero does not prevent later molecules from appearing; the readout counts only replicates at zero at the end of the horizon.

10
1.0
0.20
0.05
Complete replicates120 / 120
Final empirical mean2.82
Final deterministic closure2.90
Replicates ending at zero4 / 120 (3.3 %)
Adjust production, degradation and dimerization. Paths are generated using Gillespie reaction times and types; the deterministic curve approximates means rather than giving an exact expected path when a reaction is nonlinear.

Rates, holding times and the jump chain

On a finite space, the rate matrix or generator Q=(qij)Q=(q_{ij}) satisfies qij≥0q_{ij}\ge0 for i≠ji\ne j and qii=−∑j≠iqijq_{ii}=-\sum_{j\ne i}q_{ij}. For h↓0h\downarrow0,

P(Xt+h=j∣Xt=i)=qijh+o(h)(i≠j),P(Xt+h=i∣Xt=i)=1+qiih+o(h).\Pr(X_{t+h}=j\mid X_t=i)=q_{ij}h+o(h)\quad(i\ne j),\qquad \Pr(X_{t+h}=i\mid X_t=i)=1+q_{ii}h+o(h).

Off-diagonal entries are rates, not probabilities: they can exceed one because their units are inverse time. Every row of QQ sums to zero.

The holding-time and jump-chain construction takes qi=−qiiq_i=-q_{ii}. If qi>0q_i>0, the holding time at ii is exponential with rate qiq_i and the next state j≠ij\ne i is chosen with probability qij/qiq_{ij}/q_i. If qi=0q_i=0, ii 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 qn,n+1=2nq_{n,n+1}=2^n starting at zero has independent holding times with means 2−n2^{-n}: 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 QQ alone does not establish a conservative chain.

Kolmogorov equations

Write Pij(t)=Pi(Xt=j)P_{ij}(t)=\Pr_i(X_t=j). The backward and forward Kolmogorov equations for finite QQ are

P′(t)=QP(t),P′(t)=P(t)Q,P(0)=I,P(t)=etQ.P'(t)=QP(t),\qquad P'(t)=P(t)Q,\qquad P(0)=I,\qquad P(t)=e^{tQ}.

By Chapman-Kolmogorov, P(t+h)=P(h)P(t)=P(t)P(h)P(t+h)=P(h)P(t)=P(t)P(h). Substituting P(h)=I+hQ+o(h)P(h)=I+hQ+o(h), subtracting P(t)P(t), dividing by hh 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 μ\mu is a row distribution, μ′(t)=μ(t)Q\mu'(t)=\mu(t)Q.

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 Λ≥max⁡iqi\Lambda\ge\max_i q_i and Λ>0\Lambda>0, defines P∗=I+Q/ΛP_*=I+Q/\Lambda and applies that matrix at ticks of a Poisson clock with rate Λ\Lambda. Because QQ has rows summing to zero and the bound makes the diagonal nonnegative, P∗P_* is stochastic. Clock steps i→ii\to i are virtual: they do not change the continuous-time state.

InteractiveOne clock, two representations
t = 10.0

Continuous-time chain: only actual state changes appear.

The same path, with every clock event and discrete-chain step.

  • State change
  • Virtual step

Filled circles mark real changes; open circles are clock steps leaving the state unchanged. States 0, 1 and 2 mean healthy, degraded and down. Both views use exactly the same events up to the displayed time.

Generator Q: rates by row
012
0−0.800.600.20
10.30−0.600.30
20.200.50−0.70
P = I + Q / Λ
012
00.330.500.17
10.250.500.25
20.170.420.42

The maximum exit rate of Q is 0.8. Λ ≥ 0.8 is required, so P has rows summing to 1 and nonnegative entries. The table rounds entries to two decimals, so a displayed row may not sum exactly to 1; simulation uses unrounded values. The clock has exponential waits of rate Λ; at each event the current state’s P row is sampled. Changing Λ creates a new realization: virtual steps change, but the continuous-time chain’s law remains defined by Q. Increasing Λ raises the expected number of virtual steps, although it need not rise in every particular realization.

The uniformization identity is etQ=e−Λt∑m=0∞(Λt)mPm/m!e^{tQ}=e^{-\Lambda t}\sum_{m=0}^{\infty}(\Lambda t)^m P^m/m!.

1.2
1
Displayed time10.0
Current state0
Clock events17
State changes13
Virtual steps4
Compare all clock steps with actual state changes. Changing Λ generates another realization; the continuous-time chain's law remains the same even though virtual-step frequency changes.

Conditioning on the number of ticks up to tt, which is Poisson with mean Λt\Lambda t,

etQ=e−Λt∑k=0∞(Λt)kk!P∗k.e^{tQ}=e^{-\Lambda t}\sum_{k=0}^\infty\frac{(\Lambda t)^k}{k!}P_*^k.

The equality also follows from Q=Λ(P∗−I)Q=\Lambda(P_*-I) and the fact that II commutes with P∗P_*. Truncating after KK terms leaves row mass equal to the tail P(Poisson⁡(Λt)>K)\Pr(\operatorname{Poisson}(\Lambda t)>K): this mass controls truncation error. When Λt\Lambda t is large, starting the recurrence with e−Λte^{-\Lambda t} can underflow; rescale or use another implementation.

Equilibrium and how long states are occupied

A continuous-time stationary distribution satisfies πQ=0\pi Q=0 and ∑iπi=1\sum_i\pi_i=1. For a finite irreducible chain it exists and is unique. If additionally πiqij=πjqji\pi_iq_{ij}=\pi_jq_{ji} 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 π\pi counts time. If all exit rates are positive and the jump chain has stationary distribution ν\nu, then

πi=νi/qi∑jνj/qj,νi=πiqi∑jπjqj,\pi_i=\frac{\nu_i/q_i}{\sum_j\nu_j/q_j},\qquad \nu_i=\frac{\pi_iq_i}{\sum_j\pi_jq_j},

provided the sums are finite and distributions normalized. Each visit to ii lasts 1/qi1/q_i on average: a state with slow exits occupies more time even without more visits. Absorbing states need separate treatment because qi=0q_i=0.

For expected time tit_i to reach an absorbing set, first-step analysis gives ti=1/qi+∑j≠i(qij/qi)tjt_i=1/q_i+\sum_{j\ne i}(q_{ij}/q_i)t_j outside the set and zero on it. If every transient state in a finite chain reaches the boundary almost surely, this is equivalent to −QTTt=1-Q_{TT}\vb t=\vb1. A finite solution is not guaranteed without those assumptions.

Birth and death: queues

A birth-death process only changes from nn to n+1n+1 at rate λn\lambda_n or from nn to n−1n-1 at rate μn\mu_n. If the rates are positive where appropriate, detailed balance gives

πn=π0∏k=1nλk−1μk,π0−1=1+∑n≥1∏k=1nλk−1μk.\pi_n=\pi_0\prod_{k=1}^n\frac{\lambda_{k-1}}{\mu_k},\qquad \pi_0^{-1}=1+\sum_{n\ge1}\prod_{k=1}^n\frac{\lambda_{k-1}}{\mu_k}.

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 λ\lambda and exponential service at rate μ\mu. With ρ=λ/μ<1\rho=\lambda/\mu<1, πn=(1−ρ)ρn\pi_n=(1-\rho)\rho^n and the mean number in the system is L=ρ/(1−ρ)L=\rho/(1-\rho). The mean number waiting, excluding service, is Lq=ρ2/(1−ρ)L_q=\rho^2/(1-\rho). By Little’s law in steady state, L=λWL=\lambda W and Lq=λWqL_q=\lambda W_q, so W=1/(μ−λ)W=1/(\mu-\lambda) and Wq=ρ/(μ−λ)W_q=\rho/(\mu-\lambda). Times have units; ρ/(1−ρ)\rho/(1-\rho) is a customer count, not a time.

InteractiveM/M/1 near saturation
Time in hours; vertical axis counts customers in system
  • Queue path
  • Stationary mean L

The chain starts empty; the time mean exactly integrates the number in service and in queue during the observed interval. It may therefore take time to resemble equilibrium, especially near saturation. The player shows the same history again for the given seed.

Mean wait uses only customers who have started service, including those with zero wait. Those still waiting at the end are censored and excluded, potentially biasing the mean, especially in a growing queue. Stationary formulas require λ < μ: L = ρ/(1 − ρ) counts customers, while Wq = ρ/(μ − λ) measures queue-wait hours, excluding service.

8.0
10.0
400 h
Offered load λ / μ0.80
Current number in system4
Observed time mean in system5.03
Stationary mean in system4.00
Observed queue wait at service start0.515 h
Stationary mean queue wait0.400 h
Waits still censored3
Services started3269
Seed2608
Adjust rates and compare simulated occupancy and wait with stationary values. A path started empty has a transient; with λ≥μ this infinite queue has no stationary distribution.

For M/M/c, with cc identical servers of rate μ\mu, define a=λ/μa=\lambda/\mu and ρ=λ/(cμ)<1\rho=\lambda/(c\mu)<1. Then

π0=[∑n=0c−1ann!+acc!(1−ρ)]−1,Pespera=π0acc!(1−ρ),Wq=Pesperacμ−λ.\pi_0=\left[\sum_{n=0}^{c-1}\frac{a^n}{n!}+\frac{a^c}{c!(1-\rho)}\right]^{-1},\quad P_{\mathrm{espera}}=\pi_0\frac{a^c}{c!(1-\rho)},\quad W_q=\frac{P_{\mathrm{espera}}}{c\mu-\lambda}.

Death rates are μn=min⁡(n,c)μ\mu_n=\min(n,c)\mu. If ρ≥1\rho\ge1, 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 ar(x)a_r(x) sums a0(x)=∑rar(x)a_0(x)=\sum_r a_r(x), draws an exponential wait with rate a0(x)a_0(x) and chooses channel rr with probability ar(x)/a0(x)a_r(x)/a_0(x). If a0(x)=0a_0(x)=0, 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 avieja>0a_{\mathrm{vieja}}>0 to anueva>0a_{\mathrm{nueva}}>0 at tt, its proposed time τ\tau becomes t+(avieja/anueva)(τ−t)t+(a_{\mathrm{vieja}}/a_{\mathrm{nueva}})(\tau-t): 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 TT, let NijN_{ij} count jumps from ii to jj and SiS_i be total time in ii, including the final holding time censored at TT. The log-likelihood conditional on the start is

ℓ(Q)=∑i≠jNijlog⁡qij−∑iSi∑j≠iqij.\ell(Q)=\sum_{i\ne j}N_{ij}\log q_{ij}-\sum_i S_i\sum_{j\ne i}q_{ij}.

For Si>0S_i>0, the maximum-likelihood solution is q^ij=Nij/Si\hat q_{ij}=N_{ij}/S_i; if ii was never visited, its rates are unidentified. Observing only at fixed intervals gives transitions of P(Δ)=eΔQP(\Delta)=e^{\Delta Q}: several jumps can be hidden between observations. Counting them as direct jumps with holding time Δ\Delta 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 11 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 Λt\Lambda t.

[ ]Exponential by uniformizationBrowser
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 TT, 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.

[ ]Vectorized Gillespie for a finite generatorBrowser
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 0.10.1 and repair rate 11. State k∈{0,1,2}k\in\{0,1,2\} counts operational servers; failures occur at rate 0.1k0.1k and independent simultaneous repairs at rate 2−k2-k. Both down corresponds to k=0k=0. This is a different model from one shared repairer.

[ ]Availability of two serversBrowser
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 k=0k=0 and work only with transient states 1,21,2. The first-step system uses −QTT-Q_{TT} from the original matrix; it excludes repair after reaching the target.

[ ]Time to first complete outageBrowser
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 λ=1.2\lambda=1.2 and μ=1.5\mu=1.5 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.

[ ]M/M/2 without truncating the simulated queueBrowser
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)))
[ ]Comparison with M/M/2 equilibriumBrowser
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.

[ ]State logs and rate estimationBrowser
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))
[ ]Path bootstrap and discrete observationBrowser
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 QQ 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

NumericTwo servers down
Two servers fail independently at rate 0.1 each and are repaired independently and simultaneously at rate 1 per failed server. What is the stationary probability that both are down?
NumericWaiting in the queue
In a stable M/M/1 queue, 8 customers arrive per unit time and 10 are served. What is the mean waiting time in queue, excluding service?
QuizVisits versus time
A finite irreducible continuous-time chain has positive exit rates qᵢ and its jump chain has stationary distribution ν. What is its time-stationary distribution?
ProofBackward equation
Prove: For a finite generator Q, prove P′(t)=QP(t).
0
Use Chapman-Kolmogorov and the expansion P(h)=I+hQ+o(h).

Step 1 of 3. How do you separate the first interval of duration h?

CodeSimulate the final state
Implement 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):
  pass
Shift+Enter to run
Key idea

The 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.