Module contents
Lesson 4 of 31Advanced 105 min

Mixing times, spectral gap and perfect sampling

Knowing a chain converges is not enough: we must know how long it takes. Define total-variation mixing times and bound them by coupling, the spectral gap of reversible chains, and conductance through Cheeger's inequality. Study cutoff with card shuffling and conclude with Propp and Wilson's coupling from the past, which produces exact samples from π.

After this lesson you can

  • Calculate exact mixing times for small chains and bound them by coupling for the lazy hypercube walk.
  • Relate the spectral gap to convergence speed and calculate it numerically.
  • Use conductance to diagnose bottlenecks in multimodal chains and understand why MCMC struggles with them.
  • Reproduce cutoff in riffle shuffling and the hypercube walk.
  • Implement monotone CFTP for the Ising model and verify that the samples are exact.

Before you start

Knowing it converges does not say when

A chain may have the correct limiting distribution yet remain trapped in one mode throughout the available run. For MCMC, the question is not just whether it converges but how long it takes to forget its initial state. A classic example is shuffling: when does the distribution of permutations resemble uniformity?

The figure uses the Gilbert-Shannon-Reeds mathematical model: cut the deck according to a binomial distribution and interleave the piles with probabilities proportional to their remaining sizes. Distance is calculated by grouping permutations by their number of rising sequences, rather than observing a few decks and assuming they represent all of them.

InteractiveHow much riffle shuffling mixes

A fixed order is subjected to independent Gilbert–Shannon–Reeds shuffles. The line joins distances calculated at integer shuffle counts; the vertical mark indicates the selected value.

The rising-sequence statistic groups orders with the same probability in this model. Its distribution preserves TV distance to a uniform deck; it is not a simulated sample.

  • After selected shuffles
  • Uniform order

Eulerian numbers count orders in each group; the exact shuffle formula assigns their mass. The scale 1.5 log₂ n describes the cutoff center as n grows, not a universal threshold for finite decks. Source: Bayer and Diaconis, 1992.

52
7
Exact TV distance0.33406
Asymptotic scale 1.5 log₂ n8.55 shuffles
Calculated mass1.00000
Change the number of cards and shuffles. The curve uses the exact Bayer-Diaconis formula for the GSR model. Observe the drop region and compare different distance thresholds.

For 52 cards, the table of Bayer and Diaconis gives approximately 0.9240.924, 0.6140.614, 0.3340.334 and 0.1670.167 after five, six, seven and eight shuffles respectively. Seven marks the drop region; with threshold 1/41/4 this model requires eight. The conclusion depends on the distance definition and on real shuffling resembling GSR.

Distance and mixing time

For a finite irreducible aperiodic chain with stationary distribution π\pi, define

d(t)=max⁡x∥Pt(x,⋅)−π∥TV,dˉ(t)=max⁡x,y∥Pt(x,⋅)−Pt(y,⋅)∥TV.d(t)=\max_x\|P^t(x,\cdot)-\pi\|_{\mathrm{TV}},\qquad \bar d(t)=\max_{x,y}\|P^t(x,\cdot)-P^t(y,\cdot)\|_{\mathrm{TV}}.

The mixing time is tmix(ε)=min⁡{t:d(t)≤ε}t_{\mathrm{mix}}(\eps)=\min\{t:d(t)\le\eps\} for 0<ε<10<\eps<1. The maximum over initial states gives a uniform guarantee; a particular run may appear to mix sooner or later. Threshold conventions should be stated: tmixt_{\mathrm{mix}} often abbreviates tmix(1/4)t_{\mathrm{mix}}(1/4).

A transition does not increase total variation distance between distributions. For any difference with zero total mass, applying PP averages its contributions and the triangle inequality bounds the norm L1L^1. Therefore d(t+1)≤d(t)d(t+1)\le d(t). Also d(t)≤dˉ(t)≤2d(t)d(t)\le\bar d(t)\le2d(t), by convexity with respect to π\pi and the triangle inequality.

For submultiplicativity, take a maximal coupling of Pm(x,⋅)P^m(x,\cdot) and Pm(y,⋅)P^m(y,\cdot), which disagrees with probability equal to their total variation distance. If it disagrees, maximally couple their distributions after another nn steps; if it agrees, use the same evolution. The final disagreement probability is at most dˉ(m)dˉ(n)\bar d(m)\bar d(n), so

dˉ(m+n)≤dˉ(m)dˉ(n).\bar d(m+n)\le\bar d(m)\bar d(n).

This result explains why a mixing bound at a fixed threshold can be amplified by repeating blocks, even if the resulting bound is not tight.

Coupling the hypercube

The coupling mixing bound says that if two copies with correct marginals agree from time TT onward, the distance between their laws at tt is at most P(T>t)\Pr(T>t). For the lazy walk on the hypercube {0,1}d\{0,1\}^d, at each step choose a coordinate uniformly and replace it with a fair bit. This is equivalent to staying put with probability 1/21/2 and, with probability 1/21/2, flipping a uniformly chosen coordinate.

Couple two copies by choosing the same coordinate and bit at each step. Once chosen, a coordinate stays equal in both forever. When all have been chosen, the copies coincide. By a union bound, the probability that any coordinate remains unchosen after tt steps is at most d(1−1/d)t≤de−t/dd(1-1/d)^t\le d e^{-t/d}. Therefore d(t)≤de−t/dd(t)\le d e^{-t/d}, and t≥dlog⁡(d/ε)t\ge d\log(d/\eps) suffices to guarantee distance at most ε\eps. This is the coupon-collector bound; it need not identify the exact mixing time.

Spectrum and conductance

For a finite reversible chain, the eigenvalues of PP are real. Order 1=λ1≥λ2≥⋯≥λN≥−11=\lambda_1\ge\lambda_2\ge\cdots\ge\lambda_N\ge-1. The spectral gap and relaxation time require distinguishing two quantities: γ=1−λ2\gamma=1-\lambda_2 and γ∗=1−max⁡j≥2∣λj∣\gamma_*=1-\max_{j\ge2}|\lambda_j|, with trel=1/γ∗t_{\mathrm{rel}}=1/\gamma_* when γ∗>0\gamma_*>0. A non-lazy chain can have an eigenvalue close to −1-1: looking only at 1−λ21-\lambda_2 would hide a slow oscillation.

For a finite irreducible, reversible and aperiodic chain with πmin⁡=min⁡xπx\pi_{\min}=\min_x\pi_x, a useful bound for 0<ε<1/20<\eps<1/2 is

(trel−1)log⁡12ε≤tmix(ε)≤⌈trel(log⁡12ε+12log⁡1πmin⁡)⌉.(t_{\mathrm{rel}}-1)\log\frac1{2\eps} \le t_{\mathrm{mix}}(\eps) \le\left\lceil t_{\mathrm{rel}}\left(\log\frac1{2\eps}+\frac12\log\frac1{\pi_{\min}}\right)\right\rceil.

The upper bound follows by expanding the initial density in the orthonormal eigenbasis of PP in L2(π)L^2(\pi) and applying Cauchy-Schwarz to pass from L2L^2 to total variation. Each nonconstant component is multiplied by a power of its eigenvalue. The lower bound takes an eigenvector associated with the largest nontrivial modulus and uses the fact that its expectation decays as λt\lambda^t. These expressions and assumptions appear in Theorems 12.4 and 12.5 of Levin, Peres and Wilmer.

The spectrum quantifies slowness; geometry can explain its origin. For SS with 0<π(S)≤1/20<\pi(S)\le1/2, the outward stationary flow is Q(S,Sc)=∑i∈S,j∉SπiPijQ(S,S^c)=\sum_{i\in S,j\notin S}\pi_iP_{ij}. The conductance is

Φ=min⁡0<π(S)≤1/2Q(S,Sc)π(S).\Phi=\min_{0<\pi(S)\le1/2}\frac{Q(S,S^c)}{\pi(S)}.

A low-conductance cut retains mass in a region. Cheeger’s inequality for finite irreducible reversible chains says Φ2/2≤1−λ2≤2Φ\Phi^2/2\le1-\lambda_2\le2\Phi. It refers to the ordinary gap, not automatically the absolute gap. If the chain is lazy with nonnegative spectrum, the two coincide. The upper half follows by testing a centered cut indicator in the Rayleigh quotient; the lower half requires a level-set argument and Cauchy-Schwarz, developed in Theorem 13.10 of the same reference.

InteractiveTwo communities and a bottleneck
1: 15.5 %2: 15.5 %3: 19.3 %4: 19.1 %5: 15.3 %6: 15.3 %

Rings mark a minimizing set: 1, 2, 3. Size shows the distribution after 80 steps from node 1. If there are several minimum cuts one is shown. The stationary distribution is proportional to weighted degree.

  • Maximum over starting states
  • Start at node 1

Each internal edge has weight 1; at each step the walk stays with probability 1/2 and, if it moves, chooses a neighbor by weight. Conductance enumerates subsets with stationary mass at most 1/2; mixing time uses exact maximum distance to that distribution and threshold 0.25. Crossings are a theoretical stationary expectation, not a simulated count.

0.50
80
Minimum conductance Φ0.0385
Spectral gap 1 − λ₂0.0636
Mixing time, ε = 0.2512
Maximum distance at this step0.0028
Expected crossings per 100 stationary steps3.85
Modify the connection between two regions. Compare conductance calculated over cuts, the gap and mass evolution. A particular cut gives an upper bound on minimum conductance, not always its exact value.

Low autocorrelation for one function does not demonstrate that the entire chain has mixed. If that function does not distinguish modes separated by a narrow bridge, it may seem stable while mass from one mode barely reaches the other. Canonical paths, Poincaré inequalities and log-Sobolev inequalities give other bounds; their usefulness depends on each chain’s geometry and assumptions.

Cutoff and exact shuffling

The cutoff phenomenon is a property of a family of chains of increasing size: for every ε∈(0,1)\eps\in(0,1), mixing times at ε\eps and 1−ε1-\eps are asymptotically equivalent. The transition from distance near one to distance near zero occurs in a window small relative to the central time. A single steep curve at finite size suggests the phenomenon but does not prove it.

In GSR, tt shuffles are equivalent to an aa-shuffle with a=2ta=2^t. Bayer and Diaconis show that the probability of a permutation with rr rising sequences is a−n(a+n−rn)a^{-n}\binom{a+n-r}{n}. The number of permutations with rr sequences is the Eulerian number A(n,r)A(n,r); therefore

d(t)=12∑r=1nA(n,r)∣(2t+n−rn)2tn−1n!∣.d(t)=\frac12\sum_{r=1}^{n} A(n,r)\left|\frac{\binom{2^t+n-r}{n}}{2^{tn}}-\frac1{n!}\right|.

The formula is exact for the labeled deck and GSR model; numerical calculation requires avoiding overflowing factorials and powers. The paper’s asymptotic result places cutoff around 32log⁡2n\tfrac32\log_2 n. In the refresh-update hypercube, the location is of order 12dlog⁡d\tfrac12d\log d, while the earlier coupon bound guarantees order dlog⁡dd\log d: a valid bound need not capture cutoff.

Coupling from the past

Coupling from the past (CFTP) generates an exact sample from π\pi when the construction coalesces almost surely. Fix a sequence of random transition maps for negative times up to zero. Apply the same maps from every possible state at −T-T; if all images at zero agree, return that image. Otherwise extend the past, for example from −T-T to −2T-2T, reusing maps from the interval already generated.

The proof idea first uses a deterministic horizon TT: start a chain at −T-T with law π\pi, independent of later maps. Its value at zero has law π\pi. On the event that all states coalesce from −T-T, this value agrees with the CFTP result because the stationary start is one of the tested states. As TT grows, the probability of non-coalescence tends to zero and the distance between the returned law and π\pi is bounded by that probability. The required time is determined by looking backward with the endpoint fixed at zero; changing or regenerating randomness when extending the past breaks this construction. Under almost-sure coalescence, the returned value has exactly the stationary law. The original work is by Propp and Wilson.

On a partially ordered space, if each map is monotone and minimum and maximum states exist, following those two extremes suffices: all others stay between them. Do not confuse CFTP with advancing all paths from today and stopping when they meet: selecting that time forward can bias the common state.

InteractiveCoalescence with a fixed endpoint
Time: past on the left, present at 0
  • Starts from 0
  • Starts from 1
  • Starts from 2

Segments join states at integer times; coincident lines overlap. If a window does not coalesce, no sample is delivered. At most 64 steps are shown; failure to coalesce at that limit does not prove it impossible.

What if we wait forward until they meet?

Starting from endpoints 0 and 2 and stopping at their first meeting, we calculate the state’s distribution using the absorbing pair system. Compare it with the same chain’s stationary distribution:

State 0
Forward
56.0 %
Stationary
46.2 %
State 1
Forward
11.0 %
Stationary
30.8 %
State 2
Forward
33.0 %
Stationary
23.1 %

The first-meeting distribution is (51, 10, 30) / 91; the stationary distribution is (6, 4, 3) / 13. All three possibilities use the same maps, but stopping at a future time chosen by coalescence biases the output.

4 steps
Window−4 to 0
Seed2604
U at step −10.4935
Final states from 0, 1 and 20, 1, 1
Endpoints do not yet coincide at present. Extend the past, retain the maps already used, and restart from the endpoints.
Extend the window into the past and check that previously used maps are retained. Compare with the distribution obtained by stopping at the first forward meeting.

Lab: exact mixing and bounds

The hypercube has 2d2^d states, but symmetry means it suffices to track Hamming distance from the initial vertex. If the current weight is kk, refreshing a coordinate increases the weight with probability (d−k)/(2d)(d-k)/(2d), decreases it with probability k/(2d)k/(2d), and leaves it unchanged with probability 1/21/2. The stationary distribution of this weight is Bin⁡(d,1/2)\Bin(d,1/2). Since all configurations of the same weight have equal probability, total variation between weight laws equals that between the full laws. Translation symmetry makes the distance the same from every vertex.

[ ]Hypercube: exact distance and couponsBrowser
import numpy as np
from math import comb, exp, log, cos, pi

def hipercubo_pesos(d):
    P = np.zeros((d+1, d+1))
    for k in range(d+1):
        P[k, k] = 0.5
        if k < d:
            P[k, k+1] = (d-k)/(2*d)
        if k > 0:
            P[k, k-1] = k/(2*d)
    return P

d = 8
P = hipercubo_pesos(d)
estacionaria = np.array([comb(d, k) / 2**d for k in range(d+1)])
mu = np.eye(d+1)[0]
primero = None
for t in range(81):
    tv = .5 * np.abs(mu - estacionaria).sum()
    if primero is None and tv <= .25:
        primero = t
    if t in (0, 10, 20, 30):
        print('paso, TV exacta, cota cupones:', t, round(tv, 6), round(min(1., d*(1-1/d)**t), 6))
    mu = mu @ P
print('tiempo exacto de mezcla a 1/4:', primero)
print('cota por cupones a 1/4:', int(np.ceil(d*log(4*d))))

For a cycle of NN nodes, with probability 1/21/2 of staying and 1/41/4 of moving to each neighbor, the stationary distribution is uniform and the eigenvalues are (1+cos⁡(2πk/N))/2(1+\cos(2\pi k/N))/2. The following search calculates distance from every state without assuming symmetry in advance and compares it with the spectral bound.

[ ]Cycle and spectral gapBrowser
N = 20
C = np.zeros((N, N))
for i in range(N):
    C[i, i] = .5
    C[i, (i-1) % N] = C[i, (i+1) % N] = .25
pi_ciclo = np.ones(N) / N
valores = np.linalg.eigvalsh(C)
gamma = 1 - max(abs(valores[:-1]))
trel = 1 / gamma
potencia = np.eye(N)
tiempo = None
for t in range(501):
    distancia = np.max(.5 * np.abs(potencia - pi_ciclo).sum(axis=1))
    if tiempo is None and distancia <= .25:
        tiempo = t
    potencia = potencia @ C
cota = int(np.ceil(trel * (log(1/.5) + .5*log(N))))
print('hueco:', round(gamma, 8), 'relajación:', round(trel, 6))
print('mezcla exacta a 1/4:', tiempo, 'cota espectral:', cota)
print('fórmula del hueco:', round((1-cos(2*pi/N))/2, 8))

For small graphs we can calculate conductance exhaustively. The code requires a positive stationary distribution of a reversible chain; enumeration grows exponentially and does not replace approximate cut algorithms on large graphs. Cheeger’s inequality is checked using the ordinary gap 1−λ21-\lambda_2.

[ ]Cuts and Cheeger's inequalityBrowser
def conductancia(P, pi):
    n = len(pi)
    mejor = float('inf')
    corte = None
    for mascara in range(1, 1 << n):
        dentro = np.array([(mascara >> i) & 1 for i in range(n)], dtype=bool)
        masa = pi[dentro].sum()
        if masa > 0.5 + 1e-12:
            continue
        flujo = (pi[dentro, None] * P[np.ix_(dentro, ~dentro)]).sum()
        valor = flujo / masa
        if valor < mejor:
            mejor, corte = valor, np.flatnonzero(dentro).tolist()
    return mejor, corte

# Paseo perezoso por un camino de 4 estados.
camino = np.array([[.5,.5,0,0],[.25,.5,.25,0],[0,.25,.5,.25],[0,0,.5,.5]])
pi_camino = np.array([1/6, 1/3, 1/3, 1/6])
phi, corte = conductancia(camino, pi_camino)
simetrica = np.sqrt(pi_camino)[:, None] * camino / np.sqrt(pi_camino)[None, :]
gamma_ordinario = 1 - np.linalg.eigvalsh(simetrica)[-2]
print('corte minimizador:', corte, 'conductancia:', round(phi, 6))
print('Cheeger:', round(phi**2/2, 6), '<=', round(gamma_ordinario, 6), '<=', round(2*phi, 6))

Lab: Ising by coupling from the past

On a finite grid with spins si∈{−1,+1}s_i\in\{-1,+1\}, ferromagnetic interaction J≥0J\ge0, field hh and inverse temperature β≥0\beta\ge0, a single-site heat-bath update uses

P(si=+1∣s−i)=11+exp⁡[−2β(J∑j∼isj+h)].\Pr(s_i=+1\mid s_{-i})=\frac{1}{1+\exp[-2\beta(J\sum_{j\sim i}s_j+h)]}.

If two configurations are ordered componentwise, using the same site and uniform draw preserves the order: the probability of setting +1+1 increases with the neighbors. It therefore suffices to track the configurations of all −1-1 and all +1+1. The implementation uses free boundaries and retains each site-uniform pair when extending the window. By default it runs CFTP until coalescence. An optional limit returns None if coalescence is not reached: it does not present an approximate configuration as an exact sample. If you impose a limit, the law of results conditional on completion before it may be biased; do not discard failures and present successes as an unconditional Gibbs sample.

The theorem’s exactness assumes ideal probabilities and randomness. On a computer we use floating-point arithmetic and a pseudorandom generator; for extreme parameters, a probability may round to zero or one and destroy positive model transitions. The code explicitly rejects that case, but finite numerical error remains for other values.

[ ]Monotone CFTP for IsingBrowser
from math import exp

def vecinos_libres(L):
    resultado = []
    for i in range(L*L):
        r, c = divmod(i, L)
        resultado.append([rr*L+cc for rr, cc in ((r-1,c),(r+1,c),(r,c-1),(r,c+1))
                          if 0 <= rr < L and 0 <= cc < L])
    return resultado

def probabilidad_mas(beta, campo):
    z = 2 * beta * campo
    if z >= 0:
        p = 1 / (1 + exp(-z))
    else:
        e = exp(z)
        p = e / (1 + e)
    if p <= 0 or p >= 1:
        raise ValueError('probabilidad redondeada a 0 o 1: reduce beta o campo')
    return p

def cftp_ising(L, beta, rng, J=1., h=0., max_ventana=None):
    if beta < 0 or J < 0:
        raise ValueError('se requieren beta y J no negativos para la monotonía')
    if L < 1 or (max_ventana is not None and max_ventana < 1):
        raise ValueError('L y el límite opcional deben ser positivos')
    vecinos = vecinos_libres(L)
    sitios = np.empty(0, dtype=int)
    uniformes = np.empty(0)
    ventana = 1
    ultima = 0
    while max_ventana is None or ventana <= max_ventana:
        ultima = ventana
        nuevos = ventana - len(sitios)
        sitios = np.concatenate((rng.integers(0, L*L, nuevos), sitios))
        uniformes = np.concatenate((rng.random(nuevos), uniformes))
        inferior = np.full(L*L, -1, dtype=np.int8)
        superior = np.ones(L*L, dtype=np.int8)
        for sitio, u in zip(sitios, uniformes):
            for estado in (inferior, superior):
                campo = J * sum(int(estado[j]) for j in vecinos[sitio]) + h
                p_mas = probabilidad_mas(beta, campo)
                estado[sitio] = 1 if u < p_mas else -1
        if np.array_equal(inferior, superior):
            return inferior.reshape(L, L), ventana
        ventana *= 2
    return None, ultima

First validate on 3×33\times3, where the 292^9 states can be enumerated. With free boundaries, each edge is counted once in the energy. Compare mean absolute magnetization of CFTP samples with its exact value and display a Monte Carlo standard error. A statistical comparison can reveal mistakes, but the algorithm’s exactness follows from the coupling argument, not from a table appearing close.

[ ]Validation against exact enumerationBrowser
def media_abs_exacta(L, beta):
    pesos, observables = [], []
    for mascara in range(1 << (L*L)):
        s = np.array([1 if mascara & (1 << i) else -1 for i in range(L*L)]).reshape(L,L)
        interaccion = int((s[:, :-1]*s[:, 1:]).sum() + (s[:-1, :]*s[1:, :]).sum())
        pesos.append(exp(beta * interaccion))
        observables.append(abs(s.mean()))
    return np.average(observables, weights=pesos)

rng = np.random.default_rng(26041)
beta = .2
muestras = []
for _ in range(400):
    s, ventana = cftp_ising(3, beta, rng)
    muestras.append(abs(s.mean()))
print('magnetización absoluta exacta:', round(media_abs_exacta(3, beta), 5))
print('media CFTP:', round(np.mean(muestras), 5))
print('error estándar Monte Carlo:', round(np.std(muestras, ddof=1)/np.sqrt(len(muestras)), 5))

Finally use the requested 32×3232\times32 grid. To keep this browser demonstration bounded, enable the optional limit and report any censoring; displayed configurations are examples subject to that limit, not an unbiased sample conditional on success. Observed windows are random realizations, not universal execution times; temperature changes dependence and can make coalescence much harder. Comparison with a long chain is an approximate diagnostic, not proof that the chain is exact. To generate exact samples without that conditioning, call cftp_ising without max_ventana and let each run finish.

[ ]32 by 32 grid and comparison chainBrowser
def gibbs_magnetizacion(L, beta, pasos, rng):
    vecinos = vecinos_libres(L)
    estado = np.ones(L*L, dtype=np.int8)
    sitios = rng.integers(0, L*L, pasos)
    uniformes = rng.random(pasos)
    for sitio, u in zip(sitios, uniformes):
        campo = sum(int(estado[j]) for j in vecinos[sitio])
        p = probabilidad_mas(beta, campo)
        estado[sitio] = 1 if u < p else -1
    return abs(estado.mean())

rng = np.random.default_rng(26042)
for beta in (0.05, 0.15):
    s, ventana = cftp_ising(32, beta, rng, max_ventana=65536)
    if s is None:
        print('beta:', beta, 'sin coalescencia hasta', ventana, 'actualizaciones')
    else:
        print('beta:', beta, 'ventana CFTP:', ventana, 'magnetización absoluta:', round(abs(s.mean()), 5))
    print('una cadena de contraste, magnetización absoluta:', round(gibbs_magnetizacion(32, beta, 30000, rng), 5))

To go beyond one path, run independent replications and compare the distribution of windows with magnetization averages from long chains. Each comparison chain first discards 80,000 updates and averages observations separated by 1,000 updates; its two halves are shown as a coarse drift diagnostic, not certification of equilibrium. For CFTP use an explicit limit so each cell finishes: the magnetization comparison is calculated only if no replication was censored and remains a finite experiment, not proof that the limit introduces no bias. For an unconditional estimate use the same protocol without a limit and wait for all replications to coalesce.

[ ]Replications and long-chain diagnosticsBrowser
def gibbs_resumen(L, beta, rng, calentamiento=80000, intervalo=1000, observaciones=40):
    vecinos = vecinos_libres(L)
    estado = np.ones(L*L, dtype=np.int8)
    total = calentamiento + intervalo * observaciones
    sitios = rng.integers(0, L*L, total)
    uniformes = rng.random(total)
    medidas = []
    for t, (sitio, u) in enumerate(zip(sitios, uniformes), 1):
        campo = sum(int(estado[j]) for j in vecinos[sitio])
        estado[sitio] = 1 if u < probabilidad_mas(beta, campo) else -1
        if t > calentamiento and (t-calentamiento) % intervalo == 0:
            medidas.append(abs(estado.mean()))
    medidas = np.asarray(medidas)
    return medidas.mean(), medidas[:observaciones//2].mean(), medidas[observaciones//2:].mean()

def comparar_replicas(beta, seed, replicas=4, limite=65536):
    rng = np.random.default_rng(seed)
    ventanas, cftp, gibbs = [], [], []
    for _ in range(replicas):
        s, ventana = cftp_ising(32, beta, rng, max_ventana=limite)
        ventanas.append(ventana)
        cftp.append(None if s is None else abs(s.mean()))
        gibbs.append(gibbs_resumen(32, beta, rng))
    return ventanas, cftp, np.array(gibbs)

def mostrar_comparacion(beta, resultado):
    ventanas, cftp, gibbs = resultado
    fallos = sum(x is None for x in cftp)
    print('beta:', beta, 'ventanas:', ventanas, 'censuradas:', fallos)
    if fallos == 0:
        print('media |magnetización| CFTP, condicionada al límite:', round(np.mean(cftp), 5))
    print('media |magnetización| Gibbs:', round(gibbs[:, 0].mean(), 5))
    print('mitades Gibbs:', np.round(gibbs[:, 1:].mean(axis=0), 5))
[ ]Replications at beta 0.05Browser
comparacion_005 = comparar_replicas(.05, 26043)
mostrar_comparacion(.05, comparacion_005)
[ ]Replications at beta 0.15Browser
comparacion_015 = comparar_replicas(.15, 26044)
mostrar_comparacion(.15, comparacion_015)

Four replications are a short check, not a precise assessment of the time distribution or proof of Gibbs equilibrium. For a stronger study increase replicas, repeat with longer warmups and runs, compare several chains initialized in opposite states, and estimate uncertainty accounting for autocorrelation. As you approach slowly mixing temperatures, report the censored fraction rather than treating failed runs as nonexistent.

Exercises

NumericCycle gap
For the lazy 20-state cycle, with stay probability 1/2 and movement probability 1/4 to each neighbor, calculate the absolute spectral gap.
NumericRelaxation on a cycle
For the lazy 20-state cycle, with stay probability 1/2 and movement probability 1/4 to each neighbor, calculate the relaxation time 1/γ*.
QuizWhy reuse the past?
Which conditions form part of the CFTP construction and its justification?

More than one answer may be correct.

ProofContraction and submultiplicativity
Prove: Prove that d(n) is non-increasing and that the maximum distance between two laws satisfies d̄(m+n) ≤ d̄(m)d̄(n).
0
Use the fact that a stochastic transition contracts total variation and maximal couplings exist on finite spaces.

Step 1 of 3. What happens when P is applied to two distributions?

ProofCoupling the hypercube
Prove: Prove the bound d(t) ≤ d(1−1/d)^t for the walk that refreshes a uniformly chosen coordinate with a fair bit.
0
Couple two chains using the same coordinate and the same bit.

Step 1 of 3. When do coordinates become equal?

CodeFind the bottleneck
Implement estimate_conductance(P, pi) by exhaustive search in a finite chain with positive pi. Return the minimum of Q(S,Sᶜ)/pi(S) over nonempty sets with mass at most 1/2. There are at most 16 states.
import numpy as np

def estimate_conductance(P, pi):
  pass
Shift+Enter to run
Key idea

Mixing time measures the worst start in a chosen distance. Coupling, spectrum and conductance give complementary bounds; cutoff describes an asymptotic transition in a family. CFTP fixes the present, preserves randomness and uses coalescence to eliminate dependence on the initial state exactly.