Algorithm Search⌘K

Algorithmresearch

Preconditioned Crank-Nicolson MCMC

Also called pCN sampler, pCN, preconditioned Crank-Nicolson.

A Metropolis-Hastings sampler whose proposal keeps a Gaussian prior invariant, so its acceptance rate does not fall as the discretization is refined.

Time
Θ(N (n + D + T)) worst · average · best
Space
Θ(N n) extra
Where
D = the cost of one prior draw; N = the number of steps; T = the cost of one misfit evaluation; n = the dimension of the discretized unknown
Properties
dimension robustexact invariancenot needs prior densityrandomized
Origin
Simon L. Cotter, Gareth O. Roberts, Andrew M. Stuart, David White, 2013

Preconditioned Crank-Nicolson (pCN) is a Metropolis-Hastings method for posteriors of the form "Gaussian prior times likelihood". From the state uu it proposes v=m0+1−β2 (u−m0)+βξv = m_0 + \sqrt{1 - \beta^2}\,(u - m_0) + \beta\xi, where ξ\xi is a fresh draw from the centred prior N(0,C)N(0, C) and β∈(0,1]\beta \in (0, 1] is a step size, and it accepts vv with probability min⁡{1,exp⁡(Φ(u)−Φ(v))}\min\{1, \exp(\Phi(u) - \Phi(v))\}, where Φ\Phi is the data misfit. The proposal leaves the prior invariant, so the prior cancels from the acceptance ratio and only the likelihood is left. This makes the method well defined on a function space, and its acceptance rate stays the same when the mesh of the discretization is refined. Random-walk Metropolis, in contrast, needs a step size that goes to zero as the dimension grows. Cotter, Roberts, Stuart and White (2013) introduced the name and the function-space view; Hairer, Stuart and Vollmer (2014) proved a dimension-independent spectral gap.

In plain words

You want samples of an unknown function that fit the data, and you started with a Gaussian guess about what such functions look like. A plain random walk adds random noise to the current function. In fine resolution almost every such step makes the function rougher than the prior allows, so almost all steps are rejected. pCN instead shrinks the current function a little toward the prior mean and adds a fresh prior-like function. If there were no data, every such step would be accepted. So the only reason to reject a step is that it fits the data worse, and that does not get harder when you refine the grid.

The problem

Sample the posterior of a Bayesian inverse problem with a Gaussian prior μ0=N(m0,C)\mu_0 = N(m_0, C) and misfit Φ(u)=12∥Γ−1/2(y−G(u))∥2\Phi(u) = \frac12\lVert\Gamma^{-1/2}(y - G(u))\rVert^2:

μy(du)=1Zexp⁡(−Φ(u)) μ0(du).\mu^y(du) = \frac1Z\exp(-\Phi(u))\,\mu_0(du).

The unknown uu may be a vector in Rn\mathbb{R}^n that comes from discretizing a function. The input is a way to evaluate Φ\Phi, a way to draw from N(0,C)N(0, C), a start u0u_0, a step size β∈(0,1]\beta \in (0, 1] and a number of steps NN. The output is a Markov chain u1,…,uNu_1, \dots, u_N whose law converges to μy\mu^y, and the rate of accepted moves.

The algorithm

  1. PCN(Phi, draw_prior, u_0, beta, N, m_0) ▷ prior N(m_0, C), draw_prior returns xi ~ N(0, C)
  2. 1u ← u_0, Phi_u ← Phi(u)
  3. 2for k = 1, ..., N
  4. 3xi ← draw_prior()
  5. 4v ← m_0 + sqrt(1 - beta²) (u - m_0) + beta xi
  6. 5Phi_v ← Phi(v)
  7. 6draw U uniform on (0, 1]; if log U < Phi_u - Phi_v
  8. 7u ← v, Phi_u ← Phi_v, count the move as accepted
  9. 8append u to the chain
  10. 9return the chain and (number of accepted moves) / N

Line L1 evaluates the misfit at the start and keeps it, so each step needs one new evaluation. Line L3 draws from the prior covariance: with a Karhunen-Loeve basis this is a sum of basis functions with independent Gaussian weights, and with a dense covariance it is LzL z with a Cholesky factor LL and z∼N(0,I)z \sim N(0, I). Line L4 is the proposal. If uu has the prior law, so does vv, because (1−β2)C+β2C=C(1 - \beta^2)C + \beta^2C = C. Lines L5 and L6 accept with probability min⁡{1,eΦ(u)−Φ(v)}\min\{1, e^{\Phi(u) - \Phi(v)}\}. The prior density is not in this ratio. Line L8 stores the current state, which is the old one after a rejection.

The name comes from the Crank-Nicolson scheme. Discretize the Langevin equation du=−(u−m0) dt+2C dWdu = -(u - m_0)\,dt + \sqrt{2C}\,dW, which has the prior as its invariant law, with the implicit midpoint rule (Crank-Nicolson) and time step δ\delta. This gives line L4 with 1−β2=(2−δ)/(2+δ)\sqrt{1 - \beta^2} = (2 - \delta)/(2 + \delta) and β2=8δ/(2+δ)2\beta^2 = 8\delta/(2 + \delta)^2. The covariance CC in the noise term is the preconditioner. The case β=1\beta = 1 is the independence sampler with the prior as proposal.

Example

A scalar problem: y=au+ηy = au + \eta with a=0.1a = 0.1, η∼N(0,0.052)\eta \sim N(0, 0.05^2), prior N(0,1)N(0, 1) and y=0.12y = 0.12. The posterior is N(0.96,0.2)N(0.96, 0.2); see the Bayesian inverse problem page. Each run has 20000 steps from u0=0u_0 = 0 with random.Random(1), and the statistics drop the first 1000 states.

β\beta acceptance sample mean sample variance
0.1 0.935 0.997 0.182
0.3 0.808 0.963 0.196
0.5 0.689 0.967 0.195
0.9 0.453 0.958 0.204
1.0 0.326 0.959 0.203

Small β\beta gives a high acceptance rate but small moves, and its estimates are the worst here. A high acceptance rate alone does not mean good mixing.

The effect of the dimension: prior variances 1/k21/k^2 for k=1,…,nk = 1, \dots, n (a Karhunen-Loeve type prior), one observation of ∑kuk/k\sum_ku_k/k with value 0.50.5 and noise standard deviation 0.10.1, β=0.3\beta = 0.3, 2000 steps, random.Random(2). Random-walk Metropolis uses the proposal u+βξu + \beta\xi with the same ξ\xi.

nn pCN acceptance random-walk acceptance
10 0.384 0.294
100 0.371 0.043
1000 0.376 0.000

pCN keeps its rate. The random walk loses it, because ∥C−1/2βξ∥2\lVert C^{-1/2}\beta\xi\rVert^2 grows like β2n\beta^2n, and the prior ratio in its acceptance test goes to zero. These are measurements with fixed seeds.

Correctness

The proof is in proofs/correctness.md. The loop has NN passes, so the method stops. If u∼N(m0,C)u \sim N(m_0, C) and vv is made by line L4, then (u,v)(u, v) and (v,u)(v, u) have the same Gaussian law, because their cross-covariance 1−β2 C\sqrt{1 - \beta^2}\,C is symmetric. So the proposal is reversible for the prior. Then

μy(du) q(u,dv) a(u,v)=Z−1min⁡{e−Φ(u),e−Φ(v)} μ0(du) q(u,dv)\mu^y(du)\,q(u, dv)\,a(u, v) = Z^{-1}\min\{e^{-\Phi(u)}, e^{-\Phi(v)}\}\,\mu_0(du)\,q(u, dv)

is symmetric in (u,v)(u, v), which is detailed balance, and the posterior is invariant. In finite dimension with finite Φ\Phi the chain is irreducible, and averages converge to posterior expectations. All this is a theorem. That the convergence speed does not depend on nn is a deeper theorem of Hairer, Stuart and Vollmer (2014), under conditions on Φ\Phi, and is cited here; the tables above are measurements.

Proof: The pCN chain stops after the given number of steps and leaves the posterior invariantfull

Setting. μ0=N(m0,C)\mu_0 = N(m_0, C) is a Gaussian prior on Rn\mathbb{R}^n with CC symmetric positive definite, Φ:Rn→R\Phi: \mathbb{R}^n \to \mathbb{R} is measurable, and Z=∫exp⁡(−Φ) dμ0Z = \int\exp(-\Phi)\,d\mu_0 is finite and positive. The target is the posterior μy(du)=Z−1exp⁡(−Φ(u)) μ0(du)\mu^y(du) = Z^{-1}\exp(-\Phi(u))\,\mu_0(du). Fix β∈(0,1]\beta \in (0, 1] and put ρ=1−β2\rho = \sqrt{1 - \beta^2}. The proposal kernel q(u,⋅)q(u, \cdot) is the law of v=m0+ρ(u−m0)+βξv = m_0 + \rho(u - m_0) + \beta\xi with ξ∼N(0,C)\xi \sim N(0, C), which is line L4. The proofs below use only Gaussian measures and densities with respect to μ0\mu_0, so they hold word for word on a separable Hilbert space with a trace-class CC.

Claim 1 (termination and output). For N≥1N \ge 1 steps, the procedure stops after exactly NN passes of lines L3 to L8, returns a list of NN states, and an acceptance rate in [0,1][0, 1].

Proof. Line L2 runs a loop of fixed length NN. Each pass draws one prior sample (L3), forms one proposal (L4), evaluates Φ\Phi once (L5), and does a constant amount of other work, so it ends if Φ\Phi ends. Line L8 appends one state per pass, and the counter of accepted moves is between 00 and NN. Line L9 returns. □\square

Claim 2 (the proposal keeps the prior and is reversible for it). If u∼μ0u \sim \mu_0 and v∼q(u,⋅)v \sim q(u, \cdot), then (u,v)(u, v) and (v,u)(v, u) have the same law. In particular v∼μ0v \sim \mu_0, and μ0(du) q(u,dv)=μ0(dv) q(v,du)\mu_0(du)\,q(u, dv) = \mu_0(dv)\,q(v, du).

Proof. Put u′=u−m0u' = u - m_0 and v′=v−m0=ρu′+βξv' = v - m_0 = \rho u' + \beta\xi, with u′∼N(0,C)u' \sim N(0, C) and ξ∼N(0,C)\xi \sim N(0, C) independent. The pair (u′,v′)(u', v') is jointly Gaussian with mean zero, and

Cov(u′)=C,Cov(v′)=ρ2C+β2C=C,Cov(u′,v′)=ρC.\mathrm{Cov}(u') = C, \qquad \mathrm{Cov}(v') = \rho^2C + \beta^2C = C, \qquad \mathrm{Cov}(u', v') = \rho C.

The last matrix is symmetric, so (v′,u′)(v', u') has the same covariance blocks as (u′,v′)(u', v'). A centred Gaussian law is fixed by its covariance, so the two pairs have the same law. Shifting by m0m_0 gives the claim. □\square

Claim 3 (the acceptance test). Given uu and vv, line L6 accepts with probability a(u,v)=min⁡{1,exp⁡(Φ(u)−Φ(v))}a(u, v) = \min\{1, \exp(\Phi(u) - \Phi(v))\}.

Proof. rng.random() is uniform on [0,1)[0, 1), so $U = 1 - $ rng.random() is uniform on (0,1](0, 1] and log⁡U\log U is finite. With d=Φ(u)−Φ(v)d = \Phi(u) - \Phi(v), the test log⁡U<d\log U < d is the event U<edU < e^d, whose probability is min⁡{1,ed}\min\{1, e^d\}. □\square

Claim 4 (detailed balance and invariance). The transition kernel of one pass,

P(u,dv)=a(u,v) q(u,dv)+r(u) δu(dv),r(u)=1−∫a(u,w) q(u,dw),P(u, dv) = a(u, v)\,q(u, dv) + r(u)\,\delta_u(dv), \qquad r(u) = 1 - \int a(u, w)\,q(u, dw),

satisfies μy(du)P(u,dv)=μy(dv)P(v,du)\mu^y(du)P(u, dv) = \mu^y(dv)P(v, du). So if the state has law μy\mu^y before a pass, it has law μy\mu^y after it.

Proof. For the moving part,

μy(du) a(u,v) q(u,dv)=Z−1e−Φ(u)min⁡{1,eΦ(u)−Φ(v)} μ0(du) q(u,dv)=Z−1min⁡{e−Φ(u),e−Φ(v)} μ0(du) q(u,dv).\mu^y(du)\,a(u, v)\,q(u, dv) = Z^{-1}e^{-\Phi(u)}\min\{1, e^{\Phi(u) - \Phi(v)}\}\,\mu_0(du)\,q(u, dv) = Z^{-1}\min\{e^{-\Phi(u)}, e^{-\Phi(v)}\}\,\mu_0(du)\,q(u, dv).

The scalar factor is symmetric in (u,v)(u, v), and by Claim 2 so is the measure μ0(du) q(u,dv)\mu_0(du)\,q(u, dv). Hence the moving part is symmetric. The staying part μy(du) r(u) δu(dv)\mu^y(du)\,r(u)\,\delta_u(dv) lives on the diagonal u=vu = v and is symmetric too. Integrating the detailed balance relation over uu gives ∫μy(du)P(u,B)=μy(B)\int\mu^y(du)P(u, B) = \mu^y(B) for every measurable BB. □\square

By Claim 3, lines L4 to L7 draw from P(uk,⋅)P(u_k, \cdot), and line L8 stores the new state, so the stored chain is a Markov chain with kernel PP and invariant law μy\mu^y. The prior density never enters the acceptance ratio. This is why the method is defined on a function space, where μ0\mu_0 has no Lebesgue density.

Claim 5 (averages converge in finite dimension). Let nn be finite and Φ\Phi be finite everywhere. Then for every μy\mu^y-integrable ff and μy\mu^y-almost every start u0u_0, 1N∑k=1Nf(uk)→∫f dμy\frac1N\sum_{k=1}^Nf(u_k) \to \int f\,d\mu^y almost surely.

Proof. The proposal q(u,⋅)q(u, \cdot) has a Gaussian density that is positive everywhere, because β>0\beta > 0 and CC is positive definite, and a(u,v)>0a(u, v) > 0 for all u,vu, v because Φ\Phi is finite. So for every set BB with μy(B)>0\mu^y(B) > 0, which has positive Lebesgue measure, P(u,B)>0P(u, B) > 0 from every uu. The chain is μy\mu^y-irreducible. It has the invariant probability measure μy\mu^y by Claim 4. A μy\mu^y-irreducible chain with an invariant probability measure satisfies the law of large numbers for μy\mu^y-almost every start; this is a standard theorem on Markov chains (Tierney 1994, Meyn and Tweedie). □\square

The theorem says nothing about the speed. The speed is what distinguishes pCN from random-walk Metropolis: Hairer, Stuart and Vollmer (2014) prove a spectral gap for pCN that does not depend on the dimension, under conditions on Φ\Phi. That result is cited, not proved here, and the test of the dimension effect in the implementation is a measurement.

Complexity

Each step does one prior draw (line L3), one linear combination of length nn (line L4) and one misfit evaluation (line L5). With DD the cost of a draw and TT that of Φ\Phi, NN steps cost Θ(N(n+D+T))\Theta(N(n + D + T)). A draw costs Θ(n)\Theta(n) with a diagonal or Karhunen-Loeve prior and Θ(n2)\Theta(n^2) with a dense Cholesky factor, which costs Θ(n3)\Theta(n^3) once. In inverse problems TT is usually a forward PDE solve and dominates everything. Storing the chain needs Θ(Nn)\Theta(Nn) space; running averages need Θ(n)\Theta(n).

Properties

  • Exact: the posterior is invariant for every β∈(0,1]\beta \in (0, 1], with no discretization bias from the Crank-Nicolson step.
  • Prior-reversible proposal: with Φ=0\Phi = 0 every proposal is accepted.
  • Robust to mesh refinement: the acceptance rate and, under conditions, the spectral gap do not depend on the dimension of the discretization.
  • Needs only Φ\Phi and prior draws. No gradient, and no prior density.
  • Scale of β\beta: acceptance rates of 0.2 to 0.4 are a common target; β\beta is tuned in a short pilot run.

Variants and improvements

  • Non-centred priors. Line L4 with m0m_0 as written; for a prior N(m0,C)N(m_0, C) the misfit is unchanged.
  • Gradient versions. pCN-Langevin (pCNL) adds a drift term with C∇ΦC\nabla\Phi, the analogue of MALA, and stays well defined on function space (Cotter et al. 2013).
  • Geometry-aware versions. Replace CC in the proposal by a covariance adapted to the posterior, such as a Laplace approximation at the MAP point, so that the step is large in directions the data do not inform and small in those they do. Dimension-independent likelihood-informed (DILI) MCMC and infinite-dimensional manifold methods follow this idea.
  • Hierarchical priors. If the prior has its own hyperparameters, update them in a Gibbs step, with care, since the prior and the hyperparameter are strongly coupled in high dimension.
  • Multilevel and delayed acceptance. Evaluate a cheap coarse model first and the expensive one only if the coarse step passes.

When to use it

Use pCN when the prior is Gaussian, the unknown is a discretized function, and you want a simple sampler that keeps working when the mesh is refined, for example for PDE-constrained inverse problems with a Gaussian random field prior. It needs no gradients. If the data are very informative, the posterior is much narrower than the prior in some directions, β\beta must be small, and mixing is slow; then use a geometry-aware variant, Hamiltonian Monte Carlo, or randomize-then-optimize. For non-Gaussian priors, transform them to a Gaussian first, or use another method.

Pitfalls

  • Using the prior density in the test of line L6. The ratio must be eΦ(u)−Φ(v)e^{\Phi(u) - \Phi(v)} only. Adding the prior ratio counts the prior twice and samples the wrong law.
  • Drawing ξ\xi in line L3 from the wrong covariance, for example N(0,I)N(0, I) when the prior is N(0,C)N(0, C). Then the proposal is no longer prior-reversible, and the chain samples the wrong law.
  • Forgetting the mean in line L4. With m0≠0m_0 \ne 0 the proposal must shrink u−m0u - m_0, not uu.
  • Recomputing Φ(u)\Phi(u) in every step instead of keeping it from line L1 or L7. This doubles the cost when Φ\Phi is a PDE solve.
  • Taking the acceptance rate from line L9 as a measure of quality. Small β\beta gives a high rate and slow mixing; use the effective sample size.
  • Using log(random()) in line L6 when the generator can return 0. Draw UU in (0,1](0, 1].

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

imgla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
preconditioned_crank_nicolson_mcmc.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preconditioned-crank-nicolson-mcmc/. The authors are listed in prov/63HRT4.jsonl.
"""Preconditioned Crank-Nicolson (pCN) MCMC.

Target: the posterior mu^y with d mu^y / d mu_0 (u) proportional to
exp(-Phi(u)), where mu_0 = N(m0, C) is a Gaussian prior and Phi is the
negative log-likelihood (the data misfit). The proposal

    v = m0 + sqrt(1 - beta^2) (u - m0) + beta xi,   xi ~ N(0, C),

leaves mu_0 invariant and is reversible with respect to it, so the
Metropolis-Hastings acceptance probability is min(1, exp(Phi(u) - Phi(v))).
The prior density never appears.
"""

import math

from imgla import cholesky, matvec


def gaussian_sampler(cov):
    """Return a function rng -> xi with xi ~ N(0, cov), using a Cholesky factor."""
    low = cholesky(cov)
    n = len(cov)

    def draw(rng):
        return matvec(low, [rng.gauss(0.0, 1.0) for _ in range(n)])

    return draw


def diagonal_sampler(variances):
    """Return a function rng -> xi with independent N(0, variances[k]) entries."""
    sd = [math.sqrt(c) for c in variances]

    def draw(rng):
        return [s * rng.gauss(0.0, 1.0) for s in sd]

    return draw


def pcn(phi, draw_prior, u0, beta, steps, rng, m0=None):
    """Run pCN for the given number of steps.

    phi: function u -> Phi(u), the negative log-likelihood.
    draw_prior: function rng -> xi ~ N(0, C).
    Returns (chain, acceptance_rate); chain[k] is the state after step k + 1.
    """
    if not 0.0 < beta <= 1.0:
        raise ValueError("beta must be in (0, 1]")
    n = len(u0)
    if m0 is None:
        m0 = [0.0] * n
    rho = math.sqrt(1.0 - beta * beta)
    u = list(u0)
    phi_u = phi(u)  # @line L1
    chain = []
    accepted = 0
    for _ in range(steps):  # @line L2
        xi = draw_prior(rng)  # @line L3
        v = [m + rho * (ui - m) + beta * x for m, ui, x in zip(m0, u, xi)]  # @line L4
        phi_v = phi(v)  # @line L5
        if math.log(1.0 - rng.random()) < phi_u - phi_v:  # @line L6
            u, phi_u = v, phi_v  # @line L7
            accepted += 1
        chain.append(u)  # @line L8
    return chain, accepted / steps  # @line L9


def random_walk_metropolis(phi, prior_precision_diag, u0, beta, steps, rng, draw_prior):
    """Random-walk Metropolis with proposal v = u + beta xi, xi ~ N(0, C), for a
    centred Gaussian prior with diagonal covariance (given by its inverse
    diagonal). Used only for comparison with pCN."""
    u = list(u0)

    def log_target(w):
        return -phi(w) - 0.5 * sum(p * wi * wi for p, wi in zip(prior_precision_diag, w))

    lu = log_target(u)
    chain = []
    accepted = 0
    for _ in range(steps):
        xi = draw_prior(rng)
        v = [ui + beta * x for ui, x in zip(u, xi)]
        lv = log_target(v)
        if math.log(1.0 - rng.random()) < lv - lu:
            u, lu = v, lv
            accepted += 1
        chain.append(u)
    return chain, accepted / steps


def linear_gaussian_misfit(a, y, sigma):
    """Phi(u) = ||A u - y||^2 / (2 sigma^2)."""

    def phi(u):
        r = matvec(a, u)
        return sum((ri - yi) ** 2 for ri, yi in zip(r, y)) / (2.0 * sigma * sigma)

    return phi


def mean_and_covariance(chain):
    """Sample mean and sample covariance (divisor N - 1) of a list of vectors."""
    k = len(chain)
    n = len(chain[0])
    mean = [sum(c[i] for c in chain) / k for i in range(n)]
    cov = [[sum((c[i] - mean[i]) * (c[j] - mean[j]) for c in chain) / (k - 1) for j in range(n)] for i in range(n)]
    return mean, cov
test_preconditioned_crank_nicolson_mcmc.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/preconditioned-crank-nicolson-mcmc/. The authors are listed in prov/63HRT4.jsonl.

import math
import random

from imgla import matmul, matvec, solve, transpose
from preconditioned_crank_nicolson_mcmc import (
    diagonal_sampler,
    gaussian_sampler,
    linear_gaussian_misfit,
    mean_and_covariance,
    pcn,
    random_walk_metropolis,
)


def test_zero_misfit_accepts_every_proposal_and_keeps_the_prior():
    # Phi = 0: the acceptance probability is min(1, exp(0)) = 1, and the
    # chain is an AR(1) process whose stationary law is the prior N(3, 4).
    chain, acc = pcn(lambda u: 0.0, diagonal_sampler([4.0]), [3.0], 0.5, 10000, random.Random(5), m0=[3.0])
    assert acc == 1.0
    assert len(chain) == 10000
    mean, cov = mean_and_covariance(chain[500:])
    assert abs(mean[0] - 3.0) < 0.15
    assert abs(cov[0][0] - 4.0) < 0.3


def test_proposal_is_reversible_with_respect_to_the_prior():
    # For the prior N(0, c) and q(u, .) = N(rho u, beta^2 c), the product
    # pi_0(u) q(u, v) is symmetric in (u, v).
    c, beta = 2.5, 0.4
    rho = math.sqrt(1.0 - beta * beta)

    def log_joint(u, v):
        return -u * u / (2.0 * c) - (v - rho * u) ** 2 / (2.0 * beta * beta * c)

    rng = random.Random(3)
    for _ in range(50):
        u, v = rng.uniform(-4.0, 4.0), rng.uniform(-4.0, 4.0)
        assert abs(log_joint(u, v) - log_joint(v, u)) < 1e-12


def test_scalar_linear_gaussian_posterior():
    # y = a u + e, u ~ N(0, 1), e ~ N(0, sigma^2): the posterior is
    # N(0.96, 0.2) for a = 0.1, sigma = 0.05, y = 0.12.
    phi = linear_gaussian_misfit([[0.1]], [0.12], 0.05)
    chain, acc = pcn(phi, diagonal_sampler([1.0]), [0.0], 0.5, 12000, random.Random(1))
    mean, cov = mean_and_covariance(chain[1000:])
    assert 0.5 < acc < 0.9
    assert abs(mean[0] - 0.96) < 0.05
    assert abs(cov[0][0] - 0.2) < 0.03


def test_correlated_prior_two_dimensional_posterior():
    c0 = [[1.0, 0.5], [0.5, 1.0]]
    a = [[1.0, 1.0]]
    y = [1.0]
    sigma = 0.5
    prec = solve(c0, [[1.0, 0.0], [0.0, 1.0]])
    ata = matmul(transpose(a), a)
    post_prec = [[ata[i][j] / sigma ** 2 + prec[i][j] for j in range(2)] for i in range(2)]
    c_post = solve(post_prec, [[1.0, 0.0], [0.0, 1.0]])
    m_post = matvec(c_post, [v / sigma ** 2 for v in matvec(transpose(a), y)])
    chain, _ = pcn(linear_gaussian_misfit(a, y, sigma), gaussian_sampler(c0), [0.0, 0.0], 0.5, 12000, random.Random(7))
    mean, cov = mean_and_covariance(chain[1000:])
    for i in range(2):
        assert abs(mean[i] - m_post[i]) < 0.05
        for j in range(2):
            assert abs(cov[i][j] - c_post[i][j]) < 0.05


def test_acceptance_does_not_degrade_with_dimension():
    # Prior variances 1/k^2 and one observation of sum_k u_k / k. pCN keeps
    # its acceptance rate as n grows; random-walk Metropolis with the same
    # step does not.
    rates = {}
    for n in (10, 100):
        g = [1.0 / k for k in range(1, n + 1)]
        var = [1.0 / k ** 2 for k in range(1, n + 1)]

        def phi(u, g=g):
            return (sum(p * q for p, q in zip(g, u)) - 0.5) ** 2 / 0.02

        _, a_pcn = pcn(phi, diagonal_sampler(var), [0.0] * n, 0.3, 600, random.Random(2))
        _, a_rwm = random_walk_metropolis(phi, [1.0 / v for v in var], [0.0] * n, 0.3, 600, random.Random(2), diagonal_sampler(var))
        rates[n] = (a_pcn, a_rwm)
    assert abs(rates[10][0] - rates[100][0]) < 0.1
    assert rates[100][0] > 0.25
    assert rates[100][1] < 0.5 * rates[10][1]


def test_beta_must_be_in_the_unit_interval():
    for beta in (0.0, -0.1, 1.5):
        try:
            pcn(lambda u: 0.0, diagonal_sampler([1.0]), [0.0], beta, 10, random.Random(0))
        except ValueError:
            continue
        raise AssertionError("beta out of range was accepted")


def test_rejected_steps_repeat_the_state():
    # A huge misfit away from u = 0 makes almost every proposal fail, and a
    # failed step stores the previous state again.
    chain, acc = pcn(lambda u: 1e6 * u[0] * u[0], diagonal_sampler([1.0]), [0.0], 0.9, 200, random.Random(4))
    assert acc < 0.1
    repeats = sum(1 for p, q in zip(chain, chain[1:]) if p is q)
    assert repeats >= 200 * (1.0 - acc) - 2

History

Crank-Nicolson type proposals that keep a Gaussian reference law invariant appeared in work on sampling diffusion bridges by Beskos, Roberts, Stuart and Voss (2008). Cotter, Roberts, Stuart and White (2013) gave the name pCN, derived it from the Crank-Nicolson scheme, and placed it in the function-space framework of Bayesian inverse problems of Stuart (2010). They note that the same proposal was used earlier by Neal for Gaussian process models. Hairer, Stuart and Vollmer (2014) proved that pCN has a spectral gap that does not depend on the dimension, while that of random-walk Metropolis goes to zero.

References

  1. S. L. Cotter, G. O. Roberts, A. M. Stuart and D. White, MCMC methods for functions, modifying old algorithms to make them faster, Statistical Science 28(3), 2013, pages 424 to 446
  2. Alexandros Beskos, Gareth Roberts, Andrew Stuart and Jochen Voss, MCMC methods for diffusion bridges, Stochastics and Dynamics 8(3), 2008, pages 319 to 350
  3. Martin Hairer, Andrew M. Stuart and Sebastian J. Vollmer, Spectral gaps for a Metropolis-Hastings algorithm in infinite dimensions, Annals of Applied Probability 24(6), 2014, pages 2455 to 2490
  4. Andrew M. Stuart, Inverse problems, a Bayesian perspective, Acta Numerica 19, 2010, pages 451 to 559

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example