Module contents
Lesson 20 of 27Advanced 115 min

Bayesian inverse problems: inference in function spaces

Bayesian inverse problems describe a distribution over reconstructions. Relate Tikhonov regularization to the Gaussian posterior MAP, build Matérn-type Gaussian field priors with differential operators, approximate posteriors with Laplace and low-rank Hessians, and sample with mesh-robust pCN. Finish with Kennedy–O’Hagan calibration and model discrepancy.

After this lesson you can

  • Formulate an infinite-dimensional Bayesian inverse problem and explain why the prior must be a measure on a function space.
  • Prove that the linear Gaussian MAP is Tikhonov regularization in the norm induced by the prior covariance.
  • Build Matérn-type priors from inverses of elliptic operators discretized with finite elements.
  • Approximate the posterior by Laplace using a low-rank Hessian from Hessian–vector products and Lanczos or randomization.
  • Implement pCN and check that its acceptance rate remains stable as the mesh is refined, unlike random-walk Metropolis.
  • Set up Kennedy–O’Hagan calibration with a model discrepancy term.

Before you start

A reconstruction and its uncertainty

Before drilling an aquifer, it matters not only what conductivity you reconstruct, but which regions are informed by measurements. With Tikhonov regularization you obtained one solution. A Bayesian inverse problem assigns a distribution to possible solutions and updates that distribution with data.

InteractiveA field conditioned by sensors
  • Mean and 95% marginal
  • Sample 1
  • Sample 2

Matérn 3/2 Gaussian prior with variance one and scale 0.18. Synthetic sensor data are generated from a known function and fixed-seed noise; the exact linear-Gaussian posterior is shown.

0.20
Sensors4
Mean posterior deviation0.459
Activate sensors and change noise deviation. Compare posterior mean, marginal intervals and samples.

The figure is a synthetic linear-Gaussian example, not inference of physical conductivity. The prior at 64 positions has Matérn 3/2 covariance with variance one and scale 0.18; data are point values of an explicit function, sin⁡(2πx)+0.4cos⁡(4πx)\sin(2\pi x)+0.4\cos(4\pi x), with independent Gaussian noise and fixed seed. Mean, variances and samples are computed by exact Gaussian conditioning. Bands are 95% marginal intervals, not a simultaneous region for the whole curve. With few sensors, uncertainty can remain close to the prior far from them; the relevant distance depends on covariance.

Bayes as a change of measure

In a function space XX, let μ0\mu_0 be a prior measure and y=G(u)+ηy=G(u)+\eta with Gaussian noise of positive-definite covariance Γ\mat{\Gamma} on finitely many observations. Define

Φ(u;y)=12∥y−G(u)∥Γ−12.\Phi(u;y)=\tfrac12\norm{y-G(u)}_{\mat{\Gamma}^{-1}}^2.

If GG is measurable and constant Z(y)=∫Xe−Φ(u;y)μ0( ⁣du)Z(y)=\int_X e^{-\Phi(u;y)}\mu_0(\dd u) is positive and finite, the posterior is the measure

 ⁣dμy ⁣dμ0(u)=1Z(y)e−Φ(u;y).\frac{\dd\mu^y}{\dd\mu_0}(u)=\frac{1}{Z(y)}e^{-\Phi(u;y)}.

This is Bayes’ rule relative to the prior, not a density relative to a supposed uniform infinite-dimensional Lebesgue measure. Under additional regularity and likelihood-bound assumptions, Stuart’s formulation establishes well-posedness of the posterior measure and its dependence on data. Continuity of the posterior does not mean every point reconstruction is stable without constraints.

A prior over functions is not an arbitrary list of node variances. It must define a measure on the chosen space and its discretizations must approximate that same measure. For example, in an orthonormal basis a Gaussian prior with variances λj=j−2\lambda_j=j^{-2} has ∑jλj<∞\sum_j\lambda_j<\infty and defines a random variable in a separable Hilbert space. Assigning independent variance one to infinitely many coordinates does not similarly define a sample with finite squared norm. Prior samples should be plausible for the phenomenon and boundary conditions, not merely convenient to compute.

Linear Gaussian: Tikhonov and the full posterior

In finite dimensions, with x∼N(m0,C)\vb{x}\sim\Normal(\vb{m}_0,\mat{C}), y∣x∼N(Ax,Γ)\vb{y}\given\vb{x}\sim\Normal(\mat{A}\vb{x},\mat{\Gamma}) and positive-definite covariance matrices, completing the square gives

Cpost=(C−1+A⊤Γ−1A)−1,mpost=m0+CA⊤(ACA⊤+Γ)−1(y−Am0).\mat{C}_{\mathrm{post}}=(\mat{C}^{-1}+\mat{A}\T\mat{\Gamma}^{-1}\mat{A})^{-1},\quad \vb{m}_{\mathrm{post}}=\vb{m}_0+ \mat{C}\mat{A}\T(\mat{A}\mat{C}\mat{A}\T+\mat{\Gamma})^{-1} (\vb{y}-\mat{A}\vb{m}_0).

Mean and mode coincide in this Gaussian case. The MAP-Tikhonov equivalence says both minimize

12∥Ax−y∥Γ−12+12∥x−m0∥C−12.\tfrac12\norm{\mat{A}\vb{x}-\vb{y}}_{\mat{\Gamma}^{-1}}^2+ \tfrac12\norm{\vb{x}-\vb{m}_0}_{\mat{C}^{-1}}^2.

The first norm measures misfit in noise units; the second expresses prior geometry. The inverse objective Hessian is the posterior covariance in this case. In an infinite space, MAP requires a definition based on small balls and the appropriate Cameron-Martin norm; there is no ordinary density over the entire space. The equality above does not justify applying an inverse-covariance norm to any prior sample, which may lie outside that space.

To derive the formula, expand the sum of the two quadratics. The Hessian is positive-definite C−1+A⊤Γ−1A\mat{C}^{-1}+\mat{A}\T\mat{\Gamma}^{-1}\mat{A}, and the linear term is C−1m0+A⊤Γ−1y\mat{C}^{-1}\vb{m}_0+\mat{A}\T\mat{\Gamma}^{-1}\vb{y}. Setting the gradient to zero gives the Gaussian center. The expression with Γ+ACA⊤\mat{\Gamma}+\mat{A}\mat{C}\mat{A}\T is equivalent and, with many unknowns and few sensors, allows a system of data size to be solved. Do not form explicit inverses: use a stable factorization.

Posterior variance does not depend on observed numerical values in this linear model with fixed covariances, although it depends on sensor positions and noise. Moving a sensor changes the observation matrix and hence covariance. In nonlinear models or with unknown hyperparameters, that independence from data is no longer general.

The posterior contains more than the MAP: it permits calculation of uncertainty, correlations and predictions of new observations. A narrow band means precision conditioned on the model and prior; it does not automatically compensate for model error or certify frequentist coverage. To evaluate coverage, repeat the experiment under a specified data mechanism and count coverage frequency.

Matérn priors from a stochastic PDE

A Matérn prior via a stochastic PDE can be formally defined on Rd\R^d by

(κ2−Δ)α/2(τu)=W,ν=α−d/2>0,(\kappa^2-\Delta)^{\alpha/2}(\tau u)=W, \qquad \nu=\alpha-d/2>0,

where WW is generalized white noise, κ,τ>0\kappa,\tau>0 and ν\nu controls regularity. The relation to Matérn Gaussian fields and their discretization is described by Lindgren, Rue and Lindström. On bounded domains boundary conditions modify covariance relative to the stationary whole-space formula.

In the P1 FEM discretization of α=2\alpha=2, call the mass M\mat{M} and stiffness G\mat{G}, and K=κ2M+G\mat{K}=\kappa^2\mat{M}+\mat{G}. With approximate diagonal mass M~\tilde{\mat{M}} in the noise covariance, a discrete precision is Q≈τ2KM~−1K\mat{Q}\approx\tau^2\mat{K}\tilde{\mat{M}}^{-1}\mat{K}. Mass lumping preserves sparsity; using the inverse of consistent mass can produce a dense matrix. Boundaries, quadrature and normalization affect samples and must be documented.

The presence of M\mat{M} is not an implementation detail. Continuous white noise is a generalized distribution; its coefficients against test functions have covariance related to the mass, not arbitrary identity at nodes. If the mesh changes without correctly carrying that covariance, prior samples can change scale under refinement. In one dimension and with α=2\alpha=2, the relation above gives ν=3/2\nu=3/2, the stationary case used in the linear figures.

Which directions do the data inform?

For a linear model define the prior-preconditioned data Hessian

H~=C1/2A⊤Γ−1AC1/2.\widetilde{\mat{H}}=\mat{C}^{1/2}\mat{A}\T \mat{\Gamma}^{-1}\mat{A}\mat{C}^{1/2}.

It is positive semidefinite. If H~=VΛV⊤\widetilde{\mat{H}}=\mat{V}\mat{\Lambda}\mat{V}\T, the posterior in whitened coordinates has variance 1/(1+λi)1/(1+\lambda_i) in each informed direction. Eigenvalues near zero barely change variance from the prior. When there are few measurements, the rank of H~\widetilde{\mat{H}} does not exceed their number.

InteractiveHow much the data inform
  • Spectrum
  • Threshold 1
  • Direction 1
  • Direction 2

Independent point observations of the Matérn 3/2 field in the previous figure; the spectrum comes from the inter-sensor matrix divided by noise variance. Zeros are drawn at the logarithmic lower limit.

4
0.30
Eigenvalues greater than 14
Gaussian mutual information4.298 nats
Add sensors or change noise. The spectrum comes from the same Matérn prior and point observations; lower curves show the two dominant spatial directions.

Eigenvalues alone do not give the KL divergence of a particular posterior from the prior: posterior mean also matters. They do determine expected mutual information in the linear-Gaussian model, 12∑ilog⁡(1+λi)\tfrac12\sum_i\log(1+\lambda_i). The figure’s readout is that expectation, measured in nats. It differs from KL for a particular data realization.

In a nonlinear problem, the low-rank Laplace approximation uses the Hessian at a MAP. With an approximate positive-semidefinite data Hessian, for example Gauss-Newton, and approximation H~≈VrΛrVr⊤\widetilde{\mat{H}}\approx\mat{V}_r\mat{\Lambda}_r\mat{V}_r\T, the whitened inverse is approximated by

(I+H~)−1≈I−Vrdiag⁡ ⁣(λi1+λi)Vr⊤.(\mat{I}+\widetilde{\mat{H}})^{-1} \approx\mat{I}-\mat{V}_r \operatorname{diag}\!\left(\frac{\lambda_i}{1+\lambda_i}\right) \mat{V}_r\T.

Hessian-vector products, Lanczos or randomized methods obtain dominant directions without constructing a full dense matrix. Truncation leaves omitted directions unchanged: check the spectrum and approximation error. A multimodal or highly asymmetric posterior can be poorly represented by one Gaussian, even if the Hessian calculation is correct.

The approximation also allows sampling. If ξ∼N(0,I)\xi\sim\Normal(0,\mat{I}), transform components within the informed subspace by factor (1+λi)−1/2(1+\lambda_i)^{-1/2}, retain orthogonal ones and multiply by C1/2\mat{C}^{1/2} before adding the MAP. That operation has covariance equal to the low-rank approximation, not the exact posterior of a nonlinear model. An exact nonlinear misfit Hessian may be indefinite far from the minimum; check that the chosen posterior Hessian is positive definite before interpreting it as Gaussian precision.

The hIPPYlib package implements adjoint algorithms and low-rank representations for PDE inverse problems; its integration with MUQ combines these tools with uncertainty and sampling methods. These are options for larger problems and do not replace checking the model and discretizations.

pCN and refinement

In coordinates with prior μ0=N(0,C)\mu_0=\Normal(0,\mat{C}), the pCN (preconditioned Crank-Nicolson) proposal is

v=1−β2 u+β ξ,ξ∼μ0,0<β≤1.v=\sqrt{1-\beta^2}\,u+\beta\,\xi,\qquad \xi\sim\mu_0,\quad 0<\beta\le1.

The joint distribution of (u,v)(u,v) when uu comes from the prior is Gaussian with both marginals μ0\mu_0 and symmetric cross-covariance 1−β2C\sqrt{1-\beta^2}\mat{C}. It is invariant under exchanging uu and vv: the proposal is reversible with respect to the prior. Thus for a posterior proportional to e−Φμ0e^{-\Phi}\mu_0, Metropolis acceptance is min⁡(1,eΦ(u)−Φ(v))\min(1,e^{\Phi(u)-\Phi(v)}). This cancellation is why pCN is defined directly on function measures; see Cotter et al..

InteractivepCN versus random walk

Prior on coefficients with variances 1/j²; the likelihood depends only on the first four whitened coefficients. Two thousand iterations after 400 warmup steps; fixed seed.

Fixed step β=0.25 in whitened coordinates. Rate and autocorrelation are estimates from these chains, not guarantees for every posterior. Rescaling the RWM step can recover acceptance at the cost of smaller jumps.

Progress0 %
RWM autocorrelation, lag 1not simulated
pCN autocorrelation, lag 1not simulated
Simulate both chains and increase dimension while keeping the step fixed. Rates and autocorrelations are estimates from one reproducible run, not general guarantees.

The figure represents a prior with variances 1/j21/j^2 and a likelihood depending only on the first four whitened coordinates. RWM proposes adding Gaussian noise with a fixed step in those coordinates and corrects for both prior and likelihood. pCN preserves the prior and corrects only the likelihood. Each chain performs 400 warmup steps and retains 2000. If the chain does not move, empirical autocorrelation is undefined and is reported as such.

Discretization invariance does not mean all problems have equal acceptance or mixing under refinement: it requires a coherent family of discretizations of a function model and a well-defined likelihood. In this example added dimensions do not enter the likelihood, isolating the difference. Reducing the RWM step can maintain higher acceptance, but then its moves per coordinate are smaller. Diagnose mixing and autocorrelation, not only acceptance. Function-space MALA and HMC also incorporate prior geometry, with additional gradient and tuning requirements.

The example shows why acceptance alone is insufficient: even pCN with reasonable acceptance can move slowly in a strongly informed direction. A short chain that looks stable may not have visited other regions of a multimodal posterior. Compare multiple seeds and relevant statistics, discard warmup and estimate effective sample sizes; if a chain is frozen, autocorrelation calculated from a constant series has no valid denominator.

Discrepancy and calibration

Kennedy-O’Hagan calibration separates simulator, discrepancy and noise:

y(x)=G(x,θ)+δ(x)+ε(x).y(x)=G(x,\theta)+\delta(x)+\eps(x).

Discrepancy δ\delta represents what the simulator does not capture; it is not simply measurement noise. A flexible discrepancy prior can absorb changes also produced by θ\theta, confounding parameters and discrepancy. Data from new regimes, additional measurements with different sensitivities, physical constraints or prior information may help, but separation depends on assumptions. Kennedy and O’Hagan develop this approach to computational-model calibration.

An extreme case makes confounding visible: if G(x,θ)=θG(x,\theta)=\theta and δ(x)=c\delta(x)=c is constant, the data inform only the sum θ+c\theta+c. Changing θ\theta by aa and cc by −a-a leaves prediction unchanged. A prior can select a combination and produce a proper posterior distribution, but does not make the separation identifiable from those data. An independent measurement of one component or a justified constraint adds information the fit alone lacks.

Lab: conditioning and measuring information

Before tackling a PDE operator, check the formulas in the linear point-sensor case. We construct the same Matérn 3/2 covariance as the first figure and condition on four synthetic data points. The posterior is computed by solving systems with Cholesky, without inverting the observation matrix.

[ ]Linear posterior on a gridBrowser
import numpy as np
from scipy.linalg import cho_factor,cho_solve

N=64
grid=np.linspace(0,1,N)
distance=np.abs(grid[:,None]-grid[None,:])
q=np.sqrt(3)*distance/.18
C=(1+q)*np.exp(-q)
sensors=np.array([6,25,38,57])
noise_std=.2
truth=np.sin(2*np.pi*grid)+.4*np.cos(4*np.pi*grid)
rng=np.random.default_rng(4)
y=truth[sensors]+rng.normal(0,noise_std,len(sensors))
K=C[np.ix_(sensors,sensors)]+noise_std**2*np.eye(len(sensors))
factor=cho_factor(K,lower=True)
cross=C[:,sensors]
mean=cross@cho_solve(factor,y)
post=C-cross@cho_solve(factor,cross.T)
print("desviaciones posteriores extrema y media:",
      np.sqrt(np.maximum(np.diag(post),0)).min(),
      np.sqrt(np.maximum(np.diag(post),0)).mean())
print("simetría y autovalor mínimo:",
      np.linalg.norm(post-post.T),np.linalg.eigvalsh(post)[0])
eig=np.linalg.eigvalsh(C[np.ix_(sensors,sensors)])/noise_std**2
print("espectro preacondicionado:",eig[::-1])
print("información mutua esperada:",.5*np.log1p(eig).sum())

This calculation checks a linear distribution, not a nonlinear conductivity posterior. Observations are generated on the same grid for this algebraic test; it is not used to support a PDE reconstruction free of inverse crime.

Lab: pCN and random walk

In whitened basis zj=uj/λjz_j=u_j/\sqrt{\lambda_j}, each coordinate’s prior is standard normal. For a likelihood depending on the first four coordinates, we can study what happens when adding prior coordinates without changing the data. The following simulation uses the same formulas as the interactive, with its own NumPy seeds.

[ ]Two proposals under refinementBrowser
target=np.array([.6,-.4,.3,-.2])
beta=.25
def phi(z):
    return np.sum((z[:4]-target)**2)/(2*.7**2)
def run_chain(dim,method,seed,steps=2400,burn=400):
    rng=np.random.default_rng(seed)
    z=rng.normal(size=dim)
    accepted=0
    draws=[]
    for t in range(steps):
        xi=rng.normal(size=dim)
        candidate=(np.sqrt(1-beta**2)*z+beta*xi if method=="pcn" else z+beta*xi)
        log_accept=phi(z)-phi(candidate)
        if method=="rwm":
            log_accept += .5*(z@z-candidate@candidate)
        if np.log(rng.uniform())<min(0.,log_accept):
            z=candidate
            if t>=burn: accepted+=1
        if t>=burn: draws.append(z[0])
    draws=np.asarray(draws)
    centered=draws-draws.mean()
    den=centered@centered
    acf=(centered[:-1]@centered[1:])/den if den>1e-12 else np.nan
    return accepted/(steps-burn),acf
for dim in (16,64,256,1024):
    pcn=np.array([run_chain(dim,"pcn",seed) for seed in (1,2,3)])
    rwm=np.array([run_chain(dim,"rwm",seed+10) for seed in (1,2,3)])
    print(dim,"aceptación pCN y RWM:",pcn[:,0].mean(),rwm[:,0].mean(),
          "acf pCN y RWM:",np.nanmean(pcn[:,1]),
          np.nan if np.isnan(rwm[:,1]).all() else np.nanmean(rwm[:,1]))

Acceptance can remain stable while autocorrelation is high. Three short chains illustrate the phenomenon; they do not prove convergence or suffice for a final estimate. In a real analysis use more chains, inspect traces, effective sample size and between-chain diagnostics, and verify that discretizations describe the same prior and observation.

Lab: Bayesian conductivity with FEM

Reuse the P1 cells and the forward and adjoint problem from lesson 19. They are copied here so the lab runs end to end: data are generated on a 13×13 mesh and reconstructed on a 7×7 mesh, with 25 sensors and known synthetic noise. The true field is fixed and contains two inclusions; it does not come from a measured aquifer.

[ ]P1 assembly from lesson 9Browser
"""Ensamblaje P1 triangular para difusión-reacción y condiciones de borde.

Índices desde cero; nodos (n,2), triángulos (m,3). k y c son constantes
por elemento o escalares. f(x,y), g(x,y), alpha(x,y), r(x,y) son funciones
vectorizadas o escalares. Se admiten triángulos en ambas orientaciones.
"""
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix


def _field(value, x, y):
    result=value(x,y) if callable(value) else value
    return np.broadcast_to(np.asarray(result,dtype=float),np.shape(x))


def element_geometry(nodes, triangles):
    nodes=np.asarray(nodes,dtype=float); tri=np.asarray(triangles,dtype=int)
    if nodes.ndim!=2 or nodes.shape[1]!=2 or tri.ndim!=2 or tri.shape[1]!=3 or len(tri)==0 or not np.all(np.isfinite(nodes)):
        raise ValueError('nodos (n,2), triángulos (m,3)')
    if np.any(tri<0) or np.any(tri>=len(nodes)):
        raise ValueError('índice de nodo fuera de rango')
    p=nodes[tri]
    J=np.stack((p[:,1]-p[:,0],p[:,2]-p[:,0]),axis=-1)
    det=np.linalg.det(J)
    scale=np.max(np.abs(J),axis=(1,2))
    if np.any(np.abs(det)<=np.finfo(float).eps*scale*scale):
        raise ValueError('triángulo degenerado')
    ref=np.array([[-1.,-1.],[1.,0.],[0.,1.]])
    gradients=np.einsum('ij,ejk->eik',ref,np.linalg.inv(J))
    return p,np.abs(det)/2,gradients


def assemble_p1(nodes, triangles, k_elem=1.0, c_elem=0.0, f=0.0):
    """Devuelve (K,C,b): rigidez, masa ponderada y carga volumétrica.

    K_ij = integral k grad(phi_i).grad(phi_j), C_ij = integral c phi_i phi_j.
    k,c son constantes por elemento; la carga usa cuadratura triangular de
    grado 2. No incorpora automáticamente condiciones de contorno.
    """
    nodes=np.asarray(nodes,dtype=float); tri=np.asarray(triangles,dtype=int)
    p,area,grad=element_geometry(nodes,tri); m=len(tri); n=len(nodes)
    k=np.broadcast_to(np.asarray(k_elem,dtype=float),(m,))
    c=np.broadcast_to(np.asarray(c_elem,dtype=float),(m,))
    if np.any(k<=0) or np.any(c<0) or not np.all(np.isfinite(k)) or not np.all(np.isfinite(c)):
        raise ValueError('se requiere k positivo y c no negativo y finitos')
    klocal=area[:,None,None]*k[:,None,None]*np.einsum('eik,ejk->eij',grad,grad)
    mass=np.ones((3,3))+np.eye(3)
    clocal=(area*c)[:,None,None]*mass[None,:,:]/12
    rows=np.broadcast_to(tri[:,:,None],(m,3,3)).ravel()
    cols=np.broadcast_to(tri[:,None,:],(m,3,3)).ravel()
    K=coo_matrix((klocal.ravel(),(rows,cols)),shape=(n,n)).tocsr()
    C=coo_matrix((clocal.ravel(),(rows,cols)),shape=(n,n)).tocsr()
    bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
    points=np.einsum('qi,eid->eqd',bary,p)
    values=_field(f,points[:,:,0],points[:,:,1])
    local=(area[:,None]/3)*np.einsum('eq,qi->ei',values,bary)
    b=np.zeros(n); np.add.at(b,tri.ravel(),local.ravel())
    return K,C,b


def assemble_boundary(nodes, edges, g=0.0, alpha=0.0, r=0.0):
    """Retorna (R,b): Neumann g y Robin k du/dn+alpha*u=r.

    Los bordes deben ser disjuntos si no se desea sumar ambas contribuciones.
    Cuadratura Gauss de dos puntos por arista.
    """
    nodes=np.asarray(nodes,dtype=float); edges=np.asarray(edges,dtype=int)
    if edges.ndim!=2 or edges.shape[1]!=2 or np.any(edges<0) or np.any(edges>=len(nodes)):
        raise ValueError('aristas (m,2) con índices válidos')
    p=nodes[edges]; length=np.linalg.norm(p[:,1]-p[:,0],axis=1)
    if np.any(length<=0): raise ValueError('arista degenerada')
    z=np.array([(1-1/np.sqrt(3))/2,(1+1/np.sqrt(3))/2])
    basis=np.stack((1-z,z),axis=1)
    points=np.einsum('qi,eid->eqd',basis,p); x,y=points[:,:,0],points[:,:,1]
    ga=_field(g,x,y); ra=_field(r,x,y); aa=_field(alpha,x,y)
    local_b=(length[:,None]/2)*np.einsum('eq,qi->ei',ga+ra,basis)
    local_R=(length[:,None,None]/2)*np.einsum('eq,qi,qj->eij',aa,basis,basis)
    m=len(edges); rows=np.broadcast_to(edges[:,:,None],(m,2,2)).ravel()
    cols=np.broadcast_to(edges[:,None,:],(m,2,2)).ravel()
    R=coo_matrix((local_R.ravel(),(rows,cols)),shape=(len(nodes),len(nodes))).tocsr()
    b=np.zeros(len(nodes));np.add.at(b,edges.ravel(),local_b.ravel())
    return R,b


def apply_dirichlet(A, b, ids, values):
    """Devuelve (A_ff,b_f,free,lift); b_f incluye -A_fD u_D."""
    A=csr_matrix(A); b=np.asarray(b,dtype=float); ids=np.asarray(ids,dtype=int)
    if A.shape[0]!=A.shape[1] or b.shape!=(A.shape[0],): raise ValueError('formas incompatibles')
    if ids.ndim!=1 or np.any(ids<0) or np.any(ids>=len(b)) or len(np.unique(ids))!=len(ids):
        raise ValueError('índices Dirichlet inválidos o repetidos')
    values=np.broadcast_to(np.asarray(values,dtype=float),ids.shape)
    lift=np.zeros(len(b));lift[ids]=values
    mask=np.ones(len(b),dtype=bool);mask[ids]=False;free=np.flatnonzero(mask)
    return A[free][:,free],(b-A@lift)[free],free,lift


def reconstruct(u_free, free, lift):
    """Inserta la solución reducida en el levantamiento y devuelve todos los nodos."""
    out=np.asarray(lift,dtype=float).copy();out[np.asarray(free,dtype=int)]=u_free
    return out
[ ]Forward and adjoint model from lesson 19Browser
import numpy as np
from scipy.optimize import minimize
from scipy.sparse.linalg import spsolve


def square_mesh(n):
    t=np.linspace(0,1,n)
    xx,yy=np.meshgrid(t,t,indexing='xy')
    nodes=np.column_stack((xx.ravel(),yy.ravel()))
    triangles=[]
    for j in range(n-1):
        for i in range(n-1):
            a=j*n+i;triangles.extend(((a,a+1,a+n+1),(a,a+n+1,a+n)))
    tri=np.asarray(triangles,dtype=int)
    boundary=np.flatnonzero((nodes[:,0]==0)|(nodes[:,0]==1)|(nodes[:,1]==0)|(nodes[:,1]==1))
    return nodes,tri,boundary

def true_field(nodes):
    x,y=nodes.T
    return 1+1.3*np.exp(-((x-.35)**2+(y-.48)**2)/.014)+1.0*np.exp(-((x-.68)**2+(y-.62)**2)/.012)

def forward(nodes,tri,boundary,k):
    K,_,b=assemble_p1(nodes,tri,k_elem=k[tri].mean(axis=1),f=1.)
    A,rhs,free,lift=apply_dirichlet(K,b,boundary,0.)
    return reconstruct(spsolve(A,rhs),free,lift),A,free

nodes,tri,boundary=square_mesh(7)
fine,ft,fb=square_mesh(13)
fine_u,_,_=forward(fine,ft,fb,true_field(fine))
obs_ids=np.array([j*7+i for j in range(1,6) for i in range(1,6)])
fine_ids=np.array([(2*j)*13+2*i for j in range(1,6) for i in range(1,6)])
sigma=.0002
data=fine_u[fine_ids]+np.random.default_rng(4).normal(0,sigma,len(obs_ids))
_,area,grads=element_geometry(nodes,tri)
edges=np.unique(np.sort(np.vstack((tri[:,[0,1]],tri[:,[1,2]],tri[:,[2,0]])),axis=1),axis=0)
alpha,beta,smooth=2.,.1,.01

def objective(k,mode):
    u,A,free=forward(nodes,tri,boundary,k)
    r=(u[obs_ids]-data)/sigma
    obj=.5*r@r
    rhs=np.zeros(len(nodes));np.add.at(rhs,obs_ids,r/sigma)
    p=np.zeros(len(nodes));p[free]=spsolve(A.T,rhs[free])
    gu=np.einsum('eik,ei->ek',grads,u[tri]);gp=np.einsum('eik,ei->ek',grads,p[tri])
    eg=-area*np.einsum('ek,ek->e',gu,gp)
    grad=np.zeros(len(nodes));np.add.at(grad,tri.ravel(),np.repeat(eg/3,3))
    diff=k[edges[:,1]]-k[edges[:,0]]
    if mode=='tik':
        obj+=.5*alpha*(diff@diff)
        dg=alpha*diff
    else:
        den=np.sqrt(diff**2+smooth**2)
        obj+=alpha*np.sum(den-smooth)
        dg=alpha*diff/den
    obj+=.5*beta*np.sum((k-1)**2)
    np.add.at(grad,edges[:,0],-dg);np.add.at(grad,edges[:,1],dg)
    grad+=beta*(k-1)
    return obj,grad

The parameter is nodal log conductivity and element conductivity is the mean of exponentiated values at its nodes. The prior uses the SPDE-section operator with κ=4, τ=2, lumped mass and natural boundary. Mean log conductivity is zero. Its marginal standard deviations are printed to assess prior scale. The MAP is obtained with the adjoint and checked with Taylor; the particular truth is not assumed to be a prior sample.

[ ]SPDE prior, adjoint and MAPBrowser
from scipy.linalg import solve_triangular
from scipy.sparse.linalg import splu

# SPDE alpha=2, natural boundary, lumped mass; tune prior scale explicitly.
G,M,_=assemble_p1(nodes,tri,k_elem=1.,c_elem=1.)
mass=np.asarray(M.sum(axis=1)).ravel()
K=4**2*M+G
Q0=(K.T @ (K.multiply((1/mass)[:,None]))).toarray()
tau=2.
Q=tau**2*Q0
L=np.linalg.cholesky(Q)
B=solve_triangular(L.T,np.eye(len(nodes)),lower=False)
print('prior std range',np.sqrt(np.diag([email protected])).min(),np.sqrt(np.diag([email protected])).max())

def data_term(m,gradient=False):
    k=np.exp(m)
    u,A,free=forward(nodes,tri,boundary,k)
    r=(u[obs_ids]-data)/sigma
    value=.5*r@r
    if not gradient:return value
    rhs=np.zeros(len(nodes)); np.add.at(rhs,obs_ids,r/sigma)
    lu=splu(A.tocsc())
    p=np.zeros(len(nodes));p[free]=lu.solve(rhs[free],trans='T')
    gu=np.einsum('eik,ei->ek',grads,u[tri]);gp=np.einsum('eik,ei->ek',grads,p[tri])
    eg=-area*np.einsum('ek,ek->e',gu,gp)
    g=np.zeros(len(nodes));np.add.at(g,tri.ravel(),np.repeat(eg/3,3))
    return value,k*g

def neglog(m):
    value,g=data_term(m,True)
    return value+.5*m@Q@m,g+Q@m

rng=np.random.default_rng(23)
direction=rng.normal(size=len(nodes));direction/=np.linalg.norm(direction)
value,gradient=neglog(np.zeros(len(nodes)))
errs=[]
for eps in (1e-2,5e-3,2.5e-3,1.25e-3):
    errs.append(abs(neglog(eps*direction)[0]-value-eps*gradient@direction))
print('MAP gradient Taylor rates',np.log2(np.array(errs[:-1])/errs[1:]))
fit=minimize(neglog,np.zeros(len(nodes)),method='L-BFGS-B',jac=True,options={'maxiter':300,'ftol':1e-10})
print('MAP success',fit.success,fit.message,'objective',value,fit.fun,'grad',np.linalg.norm(fit.jac))
mapm=fit.x

For the Gauss-Newton approximation, a Hessian-vector product requires a tangent sensitivity and an adjoint solve. The dot-product test checks that both operators are transposes. The random basis uses rank 12, eight extra vectors and two power iterations; for this small mesh the full spectrum is also built as a control. The tail shows what truncation omits. The covariance describes a local approximation, not the exact posterior.

[ ]Hessian-vector products and low-rank LaplaceBrowser
# Tangent and adjoint at MAP; J maps nodal log-conductivity to whitened data.
km=np.exp(mapm)
u,A,free=forward(nodes,tri,boundary,km)
lu=splu(A.tocsc())
gu=np.einsum('eik,ei->ek',grads,u[tri])
def tangent(v):
    delta=(km*v)[tri].mean(axis=1)
    local=area[:,None]*delta[:,None]*np.einsum('eik,ek->ei',grads,gu)
    rhs=np.zeros(len(nodes));np.add.at(rhs,tri.ravel(),-local.ravel())
    du=np.zeros(len(nodes));du[free]=lu.solve(rhs[free])
    return du[obs_ids]/sigma
def adjoint(w):
    rhs=np.zeros(len(nodes));np.add.at(rhs,obs_ids,w/sigma)
    p=np.zeros(len(nodes));p[free]=lu.solve(rhs[free],trans='T')
    gp=np.einsum('eik,ei->ek',grads,p[tri])
    eg=-area*np.einsum('ek,ek->e',gu,gp)
    g=np.zeros(len(nodes));np.add.at(g,tri.ravel(),np.repeat(eg/3,3))
    return km*g
v=rng.normal(size=len(nodes));w=rng.normal(size=len(obs_ids))
print('tangent-adjoint error',abs(tangent(v)@w-v@adjoint(w)))
def hv(v):return B.T@adjoint(tangent(B@v))

# Randomized range finder with oversampling and two power passes.
r=12; oversample=8
Omega=rng.normal(size=(len(nodes),r+oversample))
Y=np.column_stack([hv(v) for v in Omega.T])
for _ in range(2):
    basis=np.linalg.qr(Y)[0]
    Y=np.column_stack([hv(v) for v in basis.T])
basis=np.linalg.qr(Y)[0]
[email protected]_stack([hv(v) for v in basis.T])
ev,U=np.linalg.eigh((small+small.T)/2)
order=np.argsort(ev)[::-1][:r];eig=ev[order];V=basis@U[:,order]
H=np.column_stack([hv(v) for v in np.eye(len(nodes))])
exact=np.linalg.eigvalsh((H+H.T)/2)[::-1]
print('leading eigenvalues approximate',eig[:6],'exact',exact[:6], 'rank-12 tail',exact[12])
lapcov=B@(np.eye(len(nodes))-(V*(eig/(1+eig)))@V.T)@B.T
print('laplace sd range',np.sqrt(np.diag(lapcov)).min(),np.sqrt(np.diag(lapcov)).max())
lap_rng=np.random.default_rng(60)
white=lap_rng.normal(size=(2000,len(nodes)))
white-=((white@V)*(1-1/np.sqrt(1+eig)))@V.T
[email protected]
print('error medio de varianza de las muestras Laplace:',
      np.mean(np.abs(lap_draws.var(axis=0)-np.diag(lapcov))))

The pCN chain preserves the prior and accepts according to misfit change. It starts at the MAP; 200 steps are warmup and 1000 retained. Conductivity mean and variance are compared, not only log conductivity, and autocorrelation of the central coordinate is shown. The chain is deliberately short: if it mixes poorly, its quantiles and variances are not reliable posterior estimates, even with positive acceptance.

[ ]Sample and compare bandsBrowser
# pCN deliberately short: measurements reported, no convergence claim.
beta=.1;steps=1200;burn=200
z=np.linalg.solve(B,mapm); val=data_term(B@z);accepted=0;draws=[]
for t in range(steps):
    candidate=np.sqrt(1-beta**2)*z+beta*rng.normal(size=len(nodes))
    new=data_term(B@candidate)
    if np.log(rng.uniform())<min(0.,val-new):
        z=candidate;val=new
        if t>=burn:accepted+=1
    if t>=burn:draws.append(B@z)
draws=np.asarray(draws)
print('pCN acceptance',accepted/(steps-burn),'mean RMSE',np.sqrt(np.mean((np.exp(draws).mean(axis=0)-true_field(nodes))**2)))
print('Laplace vs pCN avg sd',np.sqrt(np.diag(lapcov)).mean(),draws.std(axis=0).mean())
lapvar=np.diag(lapcov)
lapmean_k=np.exp(mapm+.5*lapvar)
lapvar_k=np.expm1(lapvar)*np.exp(2*mapm+lapvar)
sample_k=np.exp(draws)
print('conductivity mean avg and variance avg Laplace,pCN',lapmean_k.mean(),sample_k.mean(),lapvar_k.mean(),sample_k.var(axis=0).mean())
mid=len(nodes)//2
z0=draws[:,mid]-draws[:,mid].mean();den=z0@z0
print('center lag1',z0[:-1]@z0[1:]/den if den else np.nan)
truth_coarse=true_field(nodes)
lap_sd=np.sqrt(np.diag(lapcov))
lap_lo,lap_hi=np.exp(mapm-1.96*lap_sd),np.exp(mapm+1.96*lap_sd)
chain_lo,chain_hi=np.quantile(np.exp(draws),[.025,.975],axis=0)
print('spatial fraction inside bands: Laplace,pCN',np.mean((lap_lo<=truth_coarse)&(truth_coarse<=lap_hi)),np.mean((chain_lo<=truth_coarse)&(truth_coarse<=chain_hi)))

The first printed coverage is the fraction of nodes of this fixed truth included in marginal bands, not universal frequentist coverage. For another limited check, six independent noises are repeated while keeping truth and the fine mesh fixed, recalculating MAP and full Gauss-Newton covariance for each. Nodes are correlated; six repetitions do not certify a 95% rate. Mesh discrepancy and a narrow prior can produce overconfident bands.

[ ]Compare conductivity means and deviationsBrowser
import matplotlib.pyplot as plt
fig,axes=plt.subplots(1,5,figsize=(15,3),constrained_layout=True)
fields=[truth_coarse,lapmean_k,sample_k.mean(axis=0),np.sqrt(lapvar_k),sample_k.std(axis=0)]
labels=['Verdad','Media Laplace','Media pCN','Desviación Laplace','Desviación pCN']
for i,(ax,field,label) in enumerate(zip(axes,fields,labels)):
    limits=(1.,2.4) if i<3 else (0.,max(np.sqrt(lapvar_k).max(),sample_k.std(axis=0).max()))
    graph=ax.tricontourf(nodes[:,0],nodes[:,1],tri,field,levels=np.linspace(*limits,12),extend='both')
    ax.set_title(label);ax.set_aspect('equal');fig.colorbar(graph,ax=ax,shrink=.7)
plt.show()
[ ]Repeat with six noise realizationsBrowser
# Six new noise realizations for the same deterministic field: approximate
# Laplace intervals are recomputed; this is not a population coverage guarantee.
cover=[]
for seed in range(30,36):
    data=fine_u[fine_ids]+np.random.default_rng(seed).normal(0,sigma,len(obs_ids))
    repeated=minimize(neglog,mapm,method='L-BFGS-B',jac=True,options={'maxiter':300,'ftol':1e-9})
    if not repeated.success:print('repeat failed',seed,repeated.message)
    km=np.exp(repeated.x)
    u,A,free=forward(nodes,tri,boundary,km);lu=splu(A.tocsc())
    gu=np.einsum('eik,ei->ek',grads,u[tri])
    H=np.column_stack([hv(v) for v in np.eye(len(nodes))])
    [email protected](np.eye(len(nodes))+(H+H.T)/2,B.T)
    sd=np.sqrt(np.maximum(np.diag(covariance),0))
    lo,hi=np.exp(repeated.x-1.96*sd),np.exp(repeated.x+1.96*sd)
    cover.append(np.mean((lo<=truth_coarse)&(truth_coarse<=hi)))
print('repeated spatial fractions',cover,'mean',np.mean(cover))

Exercises

ProofComplete the square
Prove: With prior N(0,C) and noise N(0,Γ), the linear posterior is Gaussian and its mean minimizes the generalized Tikhonov objective.
0
C and Γ are positive definite and y=Ax+η.

Step 1 of 3. What quadratic term appears in the joint negative logarithm as a function of x?

ProofWhy pCN cancels the prior
Prove: The pCN proposal is reversible with respect to the centered Gaussian prior and acceptance depends only on Φ.
0
u and ξ are independent N(0,C), v=√(1−β²)u+βξ.

Step 1 of 3. What is the joint distribution of (u,v)?

Numeric
In whitened coordinates, the posterior has zero mean and data-Hessian eigenvalues 3 and 1; other directions do not change. Calculate KL(posterior || prior), in nats.
Quiz
A simulator and flexible discrepancy produce similar changes in observations. What can help separate the parameters?
CodeA pCN chain
Implement pcn(phi,sample_prior,u0,beta,n), with 0<beta≤1. sample_prior() returns a vector from the centered Gaussian prior. Return (chain,acceptance), where chain has shape (n+1,d) and includes u0; acceptance is the accepted fraction of n proposals. Use a NumPy generator with seed 0 for acceptance decisions.
import numpy as np

def pcn(phi,sample_prior,u0,beta,n):
  return None,0.0
Shift+Enter to run
Key idea
The Bayesian approach maintains a measure on functions. Gaussian MAP recovers Tikhonov, but covariance, informed directions and samples express uncertainty that a single solution does not show.