Skip to content

Bayesian PINN in 2-D: where the data say little, the posterior says so

Bayesian bayesian_poisson_source_2d.py

An unknown heat source warms a square plate, and a field is measured at only 14 noisy sensors, all in the left half. What is the source, and how sure can we be? The posterior standard deviation is a map: small where the sensors are, large where they are not.

Two rows of three panels on the unit square. Top, the field u: the true field in cividis with the 14 sensors as white dots in the left half, the posterior mean, and the posterior standard deviation in magma, near zero around the sensors and large (about 0.2) along the right edge. Bottom, the source f: the truth with the sensors, the posterior mean, which recovers the strong red source at the lower left and the blue one at the upper left but is nearly zero on the right, and the posterior standard deviation, small around the sensors and large on the right.

Top: the field \(u\); bottom: the source \(f\). In each row the truth with the sensors, the posterior mean and the posterior standard deviation.

The problem

Poisson's equation on the unit square with an unknown source made of 16 Gaussian bumps on a \(4\times4\) grid:

\[-\Delta u = f = \sum_{k=1}^{16} c_k\,\varphi_k,\qquad u=0\ \text{on}\ \partial\Omega,\qquad c\sim\mathcal N(0, I),\]
\[p(c\mid u^\text{obs}) \propto \exp\!\Big(-\tfrac{1}{2\sigma^2}\sum_{m=1}^{14}\big(u(\mathbf x_m;c)-u^\text{obs}_m\big)^2\Big)\,\mathcal N(c;0,I) .\]

The truth is one draw from the prior, solved by finite elements on its own mesh, with noise \(\sigma=0.01\).

The jNO code

Learn the physics once. One network \(\mathbb R^2\to\mathbb R^{16}\) is trained on the PDE residual alone so that output \(k\) solves \(-\Delta u_k=\varphi_k\). The problem is linear, so \(u=\sum_k c_k u_k\) for any \(c\):

d = jno.domain.from_array({"interior": nodes, "sensors": sensors})  # collocation points and sensor positions
x, y = d.variable("interior", split=True)[:2]
xs, ys = d.variable("sensors", split=True)[:2]
bubble = lambda a, b: a * (1 - a) * b * (1 - b)  # hard u = 0 on the boundary

net = jno.nn(foundax.mlp(2, output_dim=K, hidden_dims=64, num_layers=4, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(2e-3, 800, 0.6, end_value=1e-5)))
residuals = []
for k in range(K):  # output k solves -Δu_k = φ_k
    uk = (net(x, y)[..., k] * bubble(x, y)).scalar.bind(x=x, y=y)
    residuals.append((-(uk.xx + uk.yy) - bump(k, x, y)).mse)
jno.core(residuals, domain=d).solve(EPOCHS)

Freeze it and sample the coefficients. NUTS samples \(c\) against the sensors, with likelihood_scale turning the mean squared residual into the Gaussian log-likelihood and priors.gaussian(sigma=1) the prior:

net.freeze()  # a fixed forward map: u(x, y) = Σ c_k u_k(x, y)
c = jno.np.parameter((K,), name="c").initialize(jax.nn.initializers.constant(0.0))
c.bayesian(
    blackjax.nuts,
    step_size=0.1,
    warmup=300,
    keep=500,
    num_chains=4,
    init_jitter=0.5,
    prior=jno.bayesian.priors.gaussian(sigma=1.0),  # c_k ~ N(0, 1)
    likelihood_scale=M / 2,  # the mean over M sensors becomes the sum of a Gaussian log-likelihood
)
reading = jno.np.sum(net(xs, ys) * bubble(xs, ys) * c, axis=-1, keepdims=True)
crux = jno.core([((reading - d.variable("u_obs", u_obs.reshape(1, -1, 1))) / SIGMA).mse], domain=d)
crux.solve(800)

The posterior everywhere. crux.eval sees that the expression depends on the sampled parameter and maps it over the chain, so \(u\) and \(f\) come back for every sample at every node:

grid = jno.domain.from_array({"interior": nodes})  # the posterior on the reference mesh
xg, yg = grid.variable("interior", split=True)[:2]
u_expr = jno.np.sum(net(xg, yg) * bubble(xg, yg) * c, axis=-1, keepdims=True)  # u = Σ c_k u_k
f_expr = jno.np.sum(
    jno.np.concat([bump(k, xg, yg) for k in range(K)], axis=-1) * c, axis=-1, keepdims=True
)  # f = Σ c_k φ_k
u_post, f_post = (np.asarray(v).reshape(-1, len(nodes)) for v in crux.eval([u_expr, f_expr], domain=grid))  # every sample
u_mean, u_std, f_mean, f_std = u_post.mean(0), u_post.std(0), f_post.mean(0), f_post.std(0)

Result

check result
mean posterior std of \(u\), left half / right half 0.024 / 0.102 (prior: 0.31)
95 % band contains the true \(u\) / \(f\) 93.4 % / 100 % of the nodes
NUTS against the exact Gaussian posterior: means / std differ by at most 0.026 / agree to three digits

On the right, where there are no sensors, the posterior mean of \(f\) stays close to the prior mean, zero, and its spread is large: the data do not say what the source is there, and the posterior says so.

Full script

The whole script, as it runs in the tests
"""Bayesian inverse PINN in 2-D: a source field from a few noisy sensors, with a posterior that shows where it knows.

-Δu = f on the unit square, u = 0 on the boundary, f = Σ c_k φ_k a sum of 16 Gaussian bumps. One network learns the
16 solutions u_k of -Δu_k = φ_k from the physics alone; then it is frozen and NUTS samples the coefficients c from
14 noisy sensors that all sit in the left half of the square.
"""

import blackjax
import foundax
import jax
import numpy as np
import optax
from scipy.interpolate import LinearNDInterpolator

import jno

jax.config.update("jax_enable_x64", True)  # the sampler and the surrogate's last digits want float64
run = jno.setup(__file__)
exp = jno.np.exp
G, A, W, SIGMA, M, EPOCHS = 4, 20.0, 0.12, 0.01, 14, 3000  # bumps per side, height, width, sensor noise, sensors
K = G * G
centres = [((i + 0.5) / G, (j + 0.5) / G) for i in range(G) for j in range(G)]
bump = lambda k, px, py: A * exp(-((px - centres[k][0]) ** 2 + (py - centres[k][1]) ** 2) / (2 * W**2))
rng = np.random.default_rng(1)

c_true = rng.normal(size=K)  # one draw from the prior N(0, 1)
sensors = np.column_stack([rng.uniform(0.08, 0.5, M), rng.uniform(0.08, 0.92, M)])  # left half only

ref = jno.shape.rect(0, 0, 1, 1, size=0.02).domain()  # the truth, by finite elements on its own mesh
xr, yr, _ = ref.variable("interior", split=True)
xb, yb, _ = ref.variable("boundary", split=True)
w = ref.unknown()
v = w.test()
grad = lambda q: jno.np.jacobian(q, [xr, yr])
f_true = sum(float(c) * bump(k, xr, yr) for k, c in enumerate(c_true))
u_fem = np.asarray(jno.fem([jno.np.inner(grad(w), grad(v)) - f_true * v, w(xb, yb) - 0.0], quad_degree=4).solve()).ravel()
nodes = np.asarray(ref.context["interior"]).reshape(-1, 2)
u_obs = LinearNDInterpolator(nodes, u_fem)(sensors) + SIGMA * rng.normal(size=M)  # noisy readings at the sensors

d = jno.domain.from_array({"interior": nodes, "sensors": sensors})  # collocation points and sensor positions
x, y = d.variable("interior", split=True)[:2]
xs, ys = d.variable("sensors", split=True)[:2]
bubble = lambda a, b: a * (1 - a) * b * (1 - b)  # hard u = 0 on the boundary

net = jno.nn(foundax.mlp(2, output_dim=K, hidden_dims=64, num_layers=4, activation=jax.nn.tanh, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(2e-3, 800, 0.6, end_value=1e-5)))
residuals = []
for k in range(K):  # output k solves -Δu_k = φ_k
    uk = (net(x, y)[..., k] * bubble(x, y)).scalar.bind(x=x, y=y)
    residuals.append((-(uk.xx + uk.yy) - bump(k, x, y)).mse)
jno.core(residuals, domain=d).solve(EPOCHS)

net.freeze()  # a fixed forward map: u(x, y) = Σ c_k u_k(x, y)
c = jno.np.parameter((K,), name="c").initialize(jax.nn.initializers.constant(0.0))
c.bayesian(
    blackjax.nuts,
    step_size=0.1,
    warmup=300,
    keep=500,
    num_chains=4,
    init_jitter=0.5,
    prior=jno.bayesian.priors.gaussian(sigma=1.0),  # c_k ~ N(0, 1)
    likelihood_scale=M / 2,  # the mean over M sensors becomes the sum of a Gaussian log-likelihood
)
reading = jno.np.sum(net(xs, ys) * bubble(xs, ys) * c, axis=-1, keepdims=True)
crux = jno.core([((reading - d.variable("u_obs", u_obs.reshape(1, -1, 1))) / SIGMA).mse], domain=d)
crux.solve(800)

grid = jno.domain.from_array({"interior": nodes})  # the posterior on the reference mesh
xg, yg = grid.variable("interior", split=True)[:2]
u_expr = jno.np.sum(net(xg, yg) * bubble(xg, yg) * c, axis=-1, keepdims=True)  # u = Σ c_k u_k
f_expr = jno.np.sum(
    jno.np.concat([bump(k, xg, yg) for k in range(K)], axis=-1) * c, axis=-1, keepdims=True
)  # f = Σ c_k φ_k
u_post, f_post = (np.asarray(v).reshape(-1, len(nodes)) for v in crux.eval([u_expr, f_expr], domain=grid))  # every sample
u_mean, u_std, f_mean, f_std = u_post.mean(0), u_post.std(0), f_post.mean(0), f_post.std(0)

# Reference checks, plain numpy: coverage of the truth, and the closed-form Gaussian posterior of this linear problem.
f_ref = np.asarray(crux.eval([sum(float(ck) * bump(k, xg, yg) for k, ck in enumerate(c_true))], domain=grid)[0]).ravel()
covered = lambda truth, mean, std: float(np.mean(np.abs(truth - mean) < 1.96 * std))  # share inside the 95 % band
cov_u, cov_f = covered(u_fem, u_mean, u_std), covered(f_ref, f_mean, f_std)
left = nodes[:, 0] < 0.5
print(f"u: mean std {u_std[left].mean():.4f} in the left half, {u_std[~left].mean():.4f} in the right half")
print(f"95 % band holds the truth at {cov_u:.1%} of the nodes for u, {cov_f:.1%} for f")

basis = np.asarray(crux.eval([net(xs, ys) * bubble(xs, ys)])[0]).reshape(M, K)  # u_k at the sensors
cov_c = np.linalg.inv(basis.T @ basis / SIGMA**2 + np.eye(K))  # N(0, I) prior, Gaussian noise
mean_c = cov_c @ basis.T @ u_obs / SIGMA**2
chain = np.asarray(c.posterior_samples).reshape(-1, K)
d_mean, d_std = np.abs(chain.mean(0) - mean_c).max(), chain.std(0).mean() / np.sqrt(np.diag(cov_c)).mean()
print(f"NUTS vs closed form: max |Δmean| = {d_mean:.3f}, std ratio {d_std:.3f}")

assert 0.85 <= cov_u <= 1.0 and 0.85 <= cov_f <= 1.0, (cov_u, cov_f)  # a calibrated 95 % band
assert u_std[~left].mean() > 3 * u_std[left].mean()  # the spread is large away from the sensors
assert d_mean < 0.15 and abs(d_std - 1) < 0.1  # the sampler found the right posterior