Bayesian nonparametric inference on the interaction potential in the Vlasov–Fokker–Planck equation: numerical experiments¶
Companion notebook to the paper Bayesian nonparametric inference on the interaction potential in the Vlasov–Fokker–Planck equation, by Luca Martucci, Angeliki Menegaki and Grigorios A. Pavliotis. The section numbers below are those of Section 3 of the paper.
Luca Martucci, 2026.
3.1 A Hermite–Fourier spectral solver¶
Setup and figure style, the phase-space grid and the Maxwellian-adapted Hermite basis, and the coefficient-hierarchy solver with Strang splitting.
import os, time, math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from cycler import cycler
from scipy.linalg import expm
from numpy.polynomial.hermite_e import hermeval
%config InlineBackend.figure_format = 'retina'
plt.rcParams.update({
"font.family": "STIXGeneral", "mathtext.fontset": "stix",
"font.size": 9, "axes.labelsize": 9, "axes.titlesize": 9, "legend.fontsize": 8,
"xtick.labelsize": 8, "ytick.labelsize": 8,
"axes.prop_cycle": cycler(color=['#0000CD', '#D62728', '#2CA02C', '#FF7F0E']),
"axes.linewidth": 0.6, "lines.linewidth": 1.2, "lines.markersize": 4,
"xtick.major.width": 0.6, "ytick.major.width": 0.6, "xtick.minor.width": 0.4,
"ytick.minor.width": 0.4, "xtick.major.size": 3, "ytick.major.size": 3,
"xtick.minor.size": 1.8, "ytick.minor.size": 1.8,
"legend.fancybox": False, "legend.edgecolor": "0.8", "legend.framealpha": 0.9,
"axes.grid": False, "figure.dpi": 150,
"savefig.dpi": 600, "savefig.bbox": "standard", "pdf.fonttype": 42,
})
FIG_DIR = "fig"
TEXTWIDTH = 16/2.54
os.makedirs(FIG_DIR, exist_ok=True)
def paper_figure(frac, height, **kw):
"""Figure of width frac*TEXTWIDTH and the given height (inches), laid out at its printed size;
the paper includes it at width frac*\\textwidth, that is, unscaled."""
return plt.subplots(figsize=(frac*TEXTWIDTH, height), layout="constrained", **kw)
def save_figure(fig, name):
"""Write fig/<name>.pdf (vector graphics; heatmaps embedded at 600 dpi) and display it."""
fig.savefig(os.path.join(FIG_DIR, f"{name}.pdf"))
plt.show()
def set_q_axis(ax, label=True):
"""Position axis on the torus T = R/2πZ ≃ [0, 2π)."""
ax.set_xlim(0, 2*np.pi)
ax.set_xticks(np.arange(5)*np.pi/2, ["$0$", r"$\pi/2$", r"$\pi$", r"$3\pi/2$", r"$2\pi$"])
if label:
ax.set_xlabel("$q$")
def heatmap(ax, Z, x, y, cmap, label, **kw):
"""Field Z[i, j] at the points (x[j], y[i]) of uniform grids, with a labelled colour bar."""
dx, dy = x[1]-x[0], y[1]-y[0]
im = ax.imshow(Z, origin='lower', aspect='auto', cmap=cmap, interpolation='bilinear',
extent=[x[0]-dx/2, x[-1]+dx/2, y[0]-dy/2, y[-1]+dy/2], **kw)
cb = ax.figure.colorbar(im, ax=ax, pad=0.02, aspect=25)
cb.set_label(label); cb.outline.set_linewidth(0.6)
cb.ax.tick_params(width=0.6, length=2.5)
ax.set_ylim(y[0], y[-1])
return im
# ---- quadrature and interpolation on the periodic grid ----------------------------------------
# On the grid q_j = j*dq of T the rectangle rule is the quadrature of the torus, exact for
# trigonometric polynomials of degree < Nq/2 (a trapezoidal rule on q_0,...,q_{Nq-1} would omit the
# closing interval [q_{Nq-1}, 2Ï€]); momentum integrals over a finite window use the trapezoidal rule.
trapezoid = getattr(np, "trapezoid", None) or np.trapz # np.trapz was renamed in NumPy 2.0
def torus_integral(g, dq, axis=-1):
return np.sum(g, axis=axis)*dq
def cosine_coefficients(W, q, K):
"""Cosine coefficients a_k = (1/π) ∫_T W(q) cos(kq) dq, k = 1, ..., K, of grid values W."""
dq = q[1] - q[0]
a = np.array([torus_integral(W*np.cos(kk*q), dq)/np.pi for kk in range(1, K+1)])
return np.round(a, 13) + 0.0 # rounding off the floating-point noise of exact zeros
def trig_interp(values, x, axis=-1):
"""Trigonometric interpolant of values on the grid q_j = 2Ï€j/Nq, evaluated at the points x
(to draw the pseudo-spectral solutions smoothly)."""
v = np.moveaxis(np.asarray(values, dtype=float), axis, -1)
Nq = v.shape[-1]
E = np.exp(1j*np.outer(np.fft.fftfreq(Nq, d=1/Nq), x))
if Nq % 2 == 0:
E[Nq//2] = np.cos(Nq//2*x) # symmetric Nyquist term
return np.moveaxis(np.real((np.fft.fft(v, axis=-1)/Nq) @ E), -1, axis)
q_fine = np.linspace(0, 2*np.pi, 401) # plotting grid on [0, 2Ï€]
# ---- plots shared by several experiments --------------------------------------------------------
def plot_reconstruction(ax, xi_samples, Phi_f, scale_, W_truth, rng_, n_draws=80, loc='upper left'):
"""Posterior draws (grey), the truth W_0 (solid) and the posterior mean (dashed) on q_fine;
Phi_f is the cosine basis on q_fine and W_truth the truth on the solver grid."""
for j in rng_.choice(len(xi_samples), n_draws, replace=False):
ax.plot(q_fine, W_from_xi(xi_samples[j], Phi_f, scale_), color='0.5', alpha=0.15, lw=0.6)
ax.plot(q_fine, trig_interp(W_truth, q_fine), color='C0', lw=1.4, label='$W_0$')
ax.plot(q_fine, W_from_xi(xi_samples.mean(0), Phi_f, scale_), '--', color='C3', lw=1.4,
label=r'$\widetilde{W}_N$')
set_q_axis(ax); ax.legend(loc=loc)
def plot_coefficients(ax, mean, sd, truth, loc='best'):
"""Posterior mean ± one standard deviation of the cosine coefficients, against the truth."""
pos = np.arange(1, len(mean)+1)
ax.errorbar(pos, mean, yerr=sd, fmt='o', ms=3.5, capsize=2.5, elinewidth=1,
label=r'posterior mean $\pm$ s.d.')
ax.plot(pos, truth, 'rx', ms=6, mew=1.4, label='truth')
ax.axhline(0, color='k', lw=0.4)
ax.set_xticks(pos, [f"$a_{{{m}}}$" for m in pos])
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], loc=loc) # posterior first, then the truth
MODELS = (('rho', '(M1)', 'C3', 'o'), ('f', '(M2)', 'C0', 's')) # key, name, colour and marker of each model
def plot_coefficients_models(ax, means, sds, truth, loc='best'):
"""Posterior mean ± one standard deviation of the cosine coefficients for both models, against the truth."""
pos = np.arange(1, len(truth)+1)
for (model, name, col, mk), off in zip(MODELS, (-0.13, 0.13)):
ax.errorbar(pos + off, means[model], yerr=sds[model], fmt=mk, color=col, ms=3.2, capsize=2.2, elinewidth=1,
label=f'model {name}')
ax.plot(pos, truth, 'kx', ms=6, mew=1.4, label='truth')
ax.axhline(0, color='k', lw=0.4)
ax.set_xticks(pos, [f"$a_{{{m}}}$" for m in pos]); ax.legend(loc=loc)
def plot_traces(ax, traces, burn, N, ylabel):
"""Log-likelihood traces of the chains of both models, with the burn-in and the plateau -N/2 marked. The vertical
range is set by the traces after burn-in, two standard deviations sqrt(N/2) beyond them (plus headroom for the
legend), so that the initial transients leave the plotted range."""
for model, name, col, mk in MODELS:
ax.plot(traces[model], lw=0.5, color=col, label=f'model {name}')
ax.axvline(burn, color='k', ls=':', lw=1.2, label='burn-in')
ax.axhline(-N/2, color='C2', ls='--', lw=1, label=r'$-N/2$')
sd = np.sqrt(N/2)
lo = min(min(tr[burn:].min() for tr in traces.values()), -N/2) - 2*sd
hi = max(max(tr[burn:].max() for tr in traces.values()), -N/2) + 2*sd
ax.set_ylim(lo, hi + 0.35*(hi - lo)) # headroom above the traces for the legend
ax.set_xlabel("iteration"); ax.set_ylabel(ylabel)
for line in ax.legend(loc='upper center', ncol=2).get_lines():
line.set_linewidth(1.4) # legend handles thicker than the traces
def plot_sweep_models(sweeps, W_truth, name):
"""Truncation sweep for both models: L^2 error of the posterior mean against the truncation level K (left); the
range of the posterior means over K (bands) and the posterior mean at the largest K (lines), against the truth (right)."""
fig, ax = paper_figure(0.95, 2.2, ncols=2, gridspec_kw={'width_ratios': [1, 1.6]})
for model, name_, col, mk in MODELS:
sweep = sweeps[model]; Ks = list(sweep)
ax[0].plot(Ks, [sweep[K]['errW'] for K in Ks], mk + '-', ms=3.5, color=col, label=f'model {name_}')
means = np.array([build_basis_cos(q_fine, K) @ (sweep[K]['scale']*sweep[K]['post'].mean(0)) for K in Ks])
ax[1].fill_between(q_fine, means.min(0), means.max(0), color=col, alpha=0.3, lw=0)
ax[1].plot(q_fine, means[-1], color=col, lw=1.1, label=f'model {name_}')
ax[0].set_xticks(Ks); ax[0].set_ylim(bottom=0); ax[0].legend(loc='lower right')
ax[0].set_xlabel("truncation level $K$"); ax[0].set_ylabel(r"$\|\widetilde{W}_N-W_0\|_{L^2}$")
ax[1].plot(q_fine, trig_interp(W_truth, q_fine), 'k', lw=1.6, label='$W_0$')
set_q_axis(ax[1]); ax[1].legend(loc='upper left')
save_figure(fig, name)
def gauss(x, m, sd):
return np.exp(-0.5*((x-m)/sd)**2)/(sd*np.sqrt(2*np.pi))
def plot_marginals(prior_sd, posts, truth, name=None):
"""Prior (filled) against the linearised posterior marginals of a_1, ..., a_12 for both models, with the truth
(dashed); each panel title gives the shrinkages S_k of models (M1) and (M2)."""
fig, axes = paper_figure(0.95, 3.6, nrows=3, ncols=4)
for m, ax in enumerate(axes.ravel()):
lim = 3*prior_sd[m]
xg = np.concatenate([np.linspace(-lim, lim, 801)]
+ [posts[model]['mean'][m] + np.linspace(-6, 6, 801)*posts[model]['sd'][m] for model in posts])
xg = np.sort(xg[np.abs(xg) <= lim])
ax.fill_between(xg, gauss(xg, 0, prior_sd[m]), color='C0', alpha=0.25, lw=0, label='prior') # blue of model (M2)
for model, name_, col, mk in MODELS:
ax.plot(xg, gauss(xg, posts[model]['mean'][m], posts[model]['sd'][m]), color=col, lw=1.2,
ls='-' if model == 'rho' else '--', label=f'model {name_}')
ax.axvline(truth[m], color='k', ls=':', lw=0.9, label='truth')
ax.set_xlim(-lim, lim); ax.set_ylim(bottom=0); ax.set_yticks([])
ax.xaxis.set_major_locator(MaxNLocator(nbins=4, symmetric=True))
ax.set_title(rf"$a_{{{m+1}}}$: {posts['rho']['shrink'][m]:.2f}, {posts['f']['shrink'][m]:.2f}", fontsize=8)
if m == 0:
ax.legend(fontsize=6.5, loc='upper right', handlelength=1.4)
if name:
save_figure(fig, name)
else:
plt.show()
rng_global = np.random.default_rng(0)
def make_grid(Nq, L=2*np.pi):
q = np.arange(Nq) * (L / Nq)
dq = L / Nq
k = 2*np.pi * np.fft.fftfreq(Nq, d=dq)
return q, dq, k
def hermite_eval(NH, p, beta):
# B[i, n] = e_n(p_i) = sqrt(beta)/sqrt(2 pi n!) He_n(sqrt(beta) p) exp(-beta p^2 / 2)
xi = np.sqrt(beta) * np.atleast_1d(p)
gauss = np.sqrt(beta) / np.sqrt(2*np.pi) * np.exp(-0.5*xi**2)
B = np.zeros((len(xi), NH))
for n in range(NH):
c = np.zeros(n+1); c[n] = 1.0
B[:, n] = hermeval(xi, c) / np.sqrt(float(math.factorial(n))) * gauss
return B
# quick checks of the two defining properties of e_n
q, dq, k = make_grid(48)
pp = np.linspace(-12, 12, 4000); beta_chk = 1.0
B = hermite_eval(6, pp, beta_chk)
ints = trapezoid(B, pp, axis=0) # should be (1,0,0,0,0,0)
print("int e_n dp =", np.round(ints, 4))
print("max |e_0 - M| =", np.max(np.abs(B[:,0] -
np.sqrt(beta_chk/(2*np.pi))*np.exp(-0.5*beta_chk*pp**2))))
int e_n dp = [ 1. -0. -0. -0. 0. -0.] max |e_0 - M| = 0.0
def build_linear_exponentials(k, NH, gamma, beta, dt):
Ehalf = np.empty((len(k), NH, NH), dtype=complex)
Efull = np.empty((len(k), NH, NH), dtype=complex)
n = np.arange(NH)
for ik, kk in enumerate(k):
L = np.zeros((NH, NH), dtype=complex)
L[n, n] = -gamma * n # friction (diagonal)
for m in range(NH): # streaming (tridiagonal)
if m-1 >= 0: L[m, m-1] += -(1j*kk/np.sqrt(beta)) * np.sqrt(m)
if m+1 < NH: L[m, m+1] += -(1j*kk/np.sqrt(beta)) * np.sqrt(m+1)
Ehalf[ik] = expm(0.5*dt*L)
Efull[ik] = expm(dt*L)
return Ehalf, Efull
def force_kick(c, A, tau, beta):
# exact exponential of the nilpotent force generator (N c)_n = sqrt(beta n) A c_{n-1}
NH = c.shape[0]
sb = np.sqrt(beta * np.arange(NH))
out, term = c.copy(), c.copy()
for j in range(1, NH): # nilpotent => finite sum
new = np.zeros_like(term)
new[1:] = sb[1:, None] * A[None, :] * term[:-1]
term = new * (tau / j)
out += term
if not np.any(term): break
return out
class KineticVFP:
def __init__(self, q, dq, k, NH, gamma, beta, dt, V):
self.q, self.dq, self.k = q, dq, k
self.NH, self.gamma, self.beta, self.dt = NH, gamma, beta, dt
self.dV = np.real(np.fft.ifft(1j*k*np.fft.fft(V))) # dV/dq
self.Ehalf, self.Efull = build_linear_exponentials(k, NH, gamma, beta, dt)
def force_field(self, rho, W):
Wconv_hat = self.dq * np.fft.fft(W) * np.fft.fft(rho) # W * rho
dWconv = np.real(np.fft.ifft(1j*self.k*Wconv_hat))
return -self.dV - dWconv # A = -d/dq (V + W*rho)
def linear_step(self, c, E):
chat = np.fft.fft(c, axis=1) # (NH, Nq)
chat = np.einsum('kmn,nk->mk', E, chat) # apply E_k per wavenumber
return np.real(np.fft.ifft(chat, axis=1))
def step(self, c, W):
dt = self.dt
c = force_kick(c, self.force_field(c[0], W), dt/2, self.beta)
c = self.linear_step(c, self.Efull)
c = force_kick(c, self.force_field(c[0], W), dt/2, self.beta)
return c
def solve(self, W, c_init, Nt, save_every=1):
c = c_init.copy()
saved, times = [c.copy()], [0.0]
for nstep in range(Nt):
c = self.step(c, W)
if (nstep+1) % save_every == 0:
saved.append(c.copy()); times.append((nstep+1)*self.dt)
return np.array(times), np.array(saved) # saved: (Ns, NH, Nq)
3.1.3 Validation of the solver¶
Five checks: (1) the force-free density modes against their closed form, which tests streaming, friction and the Hermite truncation together; (2)–(3) mass conservation, equilibrium stationarity and $O(\Delta t^2)$ consistency; (4) convergence in the number $N_H$ of Hermite modes with the force switched on, and the gap between the solver that generates the data and the solver of the likelihood; (5) a particle cross-check for the ground truth $W_0$.
# (1) force-free density modes against their closed form. With V = W = 0 and the local Maxwellian
# initial state rho0 x M_beta, the Fourier mode k of the density evolves as
# rho_hat(t,k) = rho_hat(0,k) exp(-k^2 (gamma t - 1 + exp(-gamma t)) / (beta gamma^2)),
# the characteristic function of the time integral of a stationary Ornstein-Uhlenbeck velocity.
# Without force the solver applies the exact exponentials of the truncated blocks L_k, so the error
# below is the error of the Hermite truncation alone.
Nq, NH = 48, 14
gamma, beta = 1.0, 1.0
q, dq, k = make_grid(Nq)
rho_test = (1 + 0.2*np.cos(q) + 0.2*np.cos(2*q) + 0.2*np.cos(3*q))/(2*np.pi)
print("Force-free density modes, max over t <= 2 of |error| / |initial amplitude|:")
for NH_test in (14, 20):
s_free = KineticVFP(q, dq, k, NH_test, gamma, beta, dt=0.02, V=np.zeros(Nq))
c_free = np.zeros((NH_test, Nq)); c_free[0] = rho_test
tt, sol_free = s_free.solve(np.zeros(Nq), c_free, Nt=100, save_every=1)
rho_hat = np.fft.fft(sol_free[:, 0, :], axis=1)/Nq
errs = []
for kk in (1, 2, 3):
exact = rho_hat[0, kk]*np.exp(-kk**2*(gamma*tt - 1 + np.exp(-gamma*tt))/(beta*gamma**2))
errs.append(np.max(np.abs(rho_hat[:, kk] - exact))/np.abs(rho_hat[0, kk]))
print(f" N_H={NH_test}: k=1: {errs[0]:.1e} k=2: {errs[1]:.1e} k=3: {errs[2]:.1e}")
Force-free density modes, max over t <= 2 of |error| / |initial amplitude|: N_H=14: k=1: 3.9e-15 k=2: 4.9e-09 k=3: 1.1e-05 N_H=20: k=1: 4.0e-15 k=2: 2.9e-15 k=3: 1.0e-09
# (2)+(3) mass conservation, equilibrium stationarity, O(dt^2)
V = -np.cos(q)
W = -np.cos(q) + 0.5*np.cos(2*q)
# self-consistent McKean-Vlasov equilibrium density via Picard iteration
rho = np.ones(Nq) / (2*np.pi)
for _ in range(500):
Wconv = np.real(np.fft.ifft(dq*np.fft.fft(W)*np.fft.fft(rho)))
new = np.exp(-beta*(V + Wconv)); new /= new.sum()*dq
if np.max(np.abs(new-rho)) < 1e-14: break
rho = new
c_eq = np.zeros((NH, Nq)); c_eq[0] = rho
solver = KineticVFP(q, dq, k, NH, gamma, beta, dt=0.02, V=V)
rho0 = 1 + 0.6*np.sin(q) + 0.3*np.cos(2*q); rho0 = np.clip(rho0, 1e-3, None); rho0 /= rho0.sum()*dq
c_init = np.zeros((NH, Nq)); c_init[0] = rho0
times, sol = solver.solve(W, c_init, Nt=100, save_every=10)
print("Mass over time:", np.round(sol[:, 0, :].sum(axis=1)*dq, 12))
# Equilibrium drift: the largest |c_n(t, q_j) - c_eq,n(q_j)| over every time step up to T = 2, all grid points q_j and
# all Hermite indices 0 <= n < N_H (N_H = 14), for the interaction W above.
print("\nEquilibrium drift vs dt (Strang 2nd order):")
for dt in [0.08, 0.04, 0.02, 0.01]:
s = KineticVFP(q, dq, k, NH, gamma, beta, dt, V)
_, traj = s.solve(W, c_eq, Nt=int(round(2.0/dt)), save_every=1)
print(f" dt={dt:.3f} max|c(t)-c_eq| = {np.max(np.abs(traj-c_eq[None])):.3e}")
Mass over time: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] Equilibrium drift vs dt (Strang 2nd order): dt=0.080 max|c(t)-c_eq| = 4.772e-04 dt=0.040 max|c(t)-c_eq| = 1.194e-04 dt=0.020 max|c(t)-c_eq| = 2.986e-05 dt=0.010 max|c(t)-c_eq| = 7.465e-06
# (4) convergence in N_H with the force switched on: the trajectory of Section 3.2.1 (W_0, rho0 x M_beta)
# at N_H = 10, 14, 20, 30 against N_H = 40, all with dt = 0.01, on the momentum window |p| <= 3.5 of
# the observations; then the gap between the solver that generates the data (N_H = 20, dt = 0.01)
# and the solver of the likelihood (N_H = 14, dt = 0.02), against the noise levels of Section 3.2.1.
W_chk = -np.cos(q) + 0.5*np.cos(2*q) - 0.25*np.cos(3*q) # the ground truth W_0 of Section 3.2.1
P_win = np.linspace(-3.5, 3.5, 141)
def trajectory(NH_, dt_):
s_ = KineticVFP(q, dq, k, NH_, gamma, beta, dt_, V)
c_ = np.zeros((NH_, Nq)); c_[0] = rho0
_, sol_ = s_.solve(W_chk, c_, Nt=int(round(2.0/dt_)), save_every=int(round(0.02/dt_)))
return sol_ # snapshots every 0.02
def f_window(sol_):
return np.einsum('tnq,pn->tqp', sol_, hermite_eval(sol_.shape[1], P_win, beta))
ref = trajectory(40, 0.01); f_ref = f_window(ref)
print("Convergence in N_H (dt = 0.01, force on), against N_H = 40:")
for NH_ in (10, 14, 20, 30):
s_ = trajectory(NH_, 0.01)
print(f" N_H={NH_:2d}: max|rho - rho_ref| = {np.max(np.abs(s_[:, 0]-ref[:, 0])):.1e} "
f"max|f - f_ref| = {np.max(np.abs(f_window(s_)-f_ref)):.1e}")
data_sol, lik_sol = trajectory(20, 0.01), trajectory(14, 0.02)
d_rho = data_sol[1:, 0] - lik_sol[1:, 0]
d_f = f_window(data_sol)[1:] - f_window(lik_sol)[1:]
print(f"data solver (N_H=20, dt=0.01) against likelihood solver (N_H=14, dt=0.02):")
print(f" max|d rho| = {np.abs(d_rho).max():.1e} (rms {np.sqrt(np.mean(d_rho**2)):.1e}), "
f"max|d f| = {np.abs(d_f).max():.1e} (rms {np.sqrt(np.mean(d_f**2)):.1e})")
Convergence in N_H (dt = 0.01, force on), against N_H = 40: N_H=10: max|rho - rho_ref| = 1.8e-04 max|f - f_ref| = 4.1e-04 N_H=14: max|rho - rho_ref| = 1.3e-05 max|f - f_ref| = 6.6e-05 N_H=20: max|rho - rho_ref| = 3.0e-07 max|f - f_ref| = 5.1e-06 N_H=30: max|rho - rho_ref| = 7.5e-10 max|f - f_ref| = 8.6e-08 data solver (N_H=20, dt=0.01) against likelihood solver (N_H=14, dt=0.02): max|d rho| = 1.6e-05 (rms 4.9e-06), max|d f| = 6.1e-05 (rms 8.4e-06)
# (5) particle cross-check, up to the horizon T = 2, for the ground truth W_0 and the initial state rho0 x M_beta of
# Section 3.2.1: the particle system with the mean-field force evaluated on the histogram of the particles at the
# grid points (nearest-grid-point assignment)
dt = 0.01
solver = KineticVFP(q, dq, k, NH, gamma, beta, dt, V)
T = 2.0; Nt = int(round(T/dt))
_, sol = solver.solve(W_chk, c_init, Nt, save_every=Nt)
rho_pde = sol[-1, 0, :]
# Histogram bins centred at the grid points, [q_j - dq/2, q_j + dq/2): the value of bin j estimates
# the density at q_j, where the convolution is evaluated and the spectral density is compared, and
# each particle feels the mean-field force at its nearest grid point.
def grid_bin(x):
return np.floor(((x + dq/2) % (2*np.pi))/dq).astype(int) % Nq
def histogram_density(x):
return np.bincount(grid_bin(x), minlength=Nq)/(len(x)*dq)
rng = np.random.default_rng(0)
n_part = 200_000
cdf = np.cumsum(rho0*dq); cdf /= cdf[-1]
qj = np.interp(rng.random(n_part), cdf, q) # q0 ~ rho0
pj = rng.standard_normal(n_part) / np.sqrt(beta) # p0 ~ Maxwellian
W_hat = np.fft.fft(W_chk)
for _ in range(Nt):
hist = histogram_density(qj)
dWconv = np.real(np.fft.ifft(1j*k*dq*W_hat*np.fft.fft(hist)))
force = -np.sin(qj) - dWconv[grid_bin(qj)] # -dV - d(W*rho), V=-cos
pj += dt*force - gamma*pj*dt + np.sqrt(2*gamma/beta*dt)*rng.standard_normal(n_part)
qj = (qj + pj*dt) % (2*np.pi)
hist_T = histogram_density(qj)
errL2 = np.sqrt(torus_integral((hist_T - rho_pde)**2, dq))
print(f"||rho_hist(T) - rho_PDE(T)||_L2 = {errL2:.4f} (density scale 1/(2 pi) = {1/(2*np.pi):.3f}; "
f"root-mean-square relative discrepancy {np.sqrt(np.mean((hist_T - rho_pde)**2))*2*np.pi:.1%})")
fig, ax = paper_figure(0.62, 2.0)
ax.plot(q_fine, trig_interp(rho0, q_fine), 'k:', lw=1.2, label=r'$\rho_0$')
ax.plot(q_fine, trig_interp(rho_pde, q_fine), color='C0', lw=1.4, label=r'$\rho^{\mathrm{PDE}}(T)$')
ax.plot(q, hist_T, 'o', color='C3', ms=3, label=r'$\rho^{\mathrm{hist}}(T)$')
set_q_axis(ax); ax.legend()
save_figure(fig, "ips_crosscheck")
||rho_hist(T) - rho_PDE(T)||_L2 = 0.0090 (density scale 1/(2 pi) = 0.159; root-mean-square relative discrepancy 2.3%)
3.1.4 Hypocoercivity in the discretised generator¶
# Spectrum of the linear streaming+friction operator L_k, wavenumber by wavenumber: the least-damped rates of the
# truncated blocks against the exact values k^2/(beta gamma), and the condition number of the leading eigenvalue.
NH_spec, gamma_spec, beta_spec = 14, 1.0, 1.0
def Lk_matrix(kk, NH, gamma, beta):
L = np.zeros((NH, NH), dtype=complex)
for m in range(NH):
L[m, m] = -gamma * m # friction (diagonal)
if m-1 >= 0: L[m, m-1] += -(1j*kk/np.sqrt(beta)) * np.sqrt(m) # streaming
if m+1 < NH: L[m, m+1] += -(1j*kk/np.sqrt(beta)) * np.sqrt(m+1)
return L
k_scan = np.arange(0, 9)
slowest = np.array([np.linalg.eigvals(Lk_matrix(kk, NH_spec, gamma_spec, beta_spec)).real.max()
for kk in k_scan])
print("k :", k_scan)
print("least-damped rate, N_H = 14 :", np.round(-slowest, 3))
print("exact rate k^2/(beta gamma) :", k_scan**2/(beta_spec*gamma_spec))
for NH_chk in (20, 40):
rates = [-np.linalg.eigvals(Lk_matrix(kk, NH_chk, gamma_spec, beta_spec)).real.max() for kk in (1, 2, 3)]
print(f"N_H={NH_chk}: least-damped rates at k=1,2,3 = " + ", ".join(f"{r:.3f}" for r in rates))
print("condition number e^{2k^2/(gamma^2 beta)} of the leading eigenvalue, k=1,...,4:",
", ".join(f"{np.exp(2*kk**2/(gamma_spec**2*beta_spec)):.1e}" for kk in (1, 2, 3, 4)))
k : [0 1 2 3 4 5 6 7 8]
least-damped rate, N_H = 14 : [0. 1. 3.674 4.112 4.228 4.278 4.304 4.32 4.33 ]
exact rate k^2/(beta gamma) : [ 0. 1. 4. 9. 16. 25. 36. 49. 64.]
N_H=20: least-damped rates at k=1,2,3 = 1.000, 4.001, 5.810
N_H=40: least-damped rates at k=1,2,3 = 1.000, 4.000, 9.000
condition number e^{2k^2/(gamma^2 beta)} of the leading eigenvalue, k=1,...,4: 7.4e+00, 3.0e+03, 6.6e+07, 7.9e+13
3.2 The statistical experiment¶
Ground truth $W_0$, the initial state $\phi=\rho_0\otimes M_\beta$, and the observation designs of both measurement models, with the noise calibrated to a common noise-to-signal ratio; the data are generated at a finer resolution than the solver of the likelihood, to avoid the inverse crime.
def generate_truth(seed=0, W_true=None, Nq=48, NH_hi=20, gamma=1.0, beta=1.0, T=2.0, dt_hi=0.01):
q, dq, k = make_grid(Nq); V = -np.cos(q)
if W_true is None:
W_true = -np.cos(q) + 0.5*np.cos(2*q) - 0.25*np.cos(3*q)
rho0 = 1 + 0.6*np.sin(q) + 0.3*np.cos(2*q); rho0 = np.clip(rho0, 1e-3, None); rho0 /= rho0.sum()*dq
c_init = np.zeros((NH_hi, Nq)); c_init[0] = rho0
solver_hi = KineticVFP(q, dq, k, NH_hi, gamma, beta, dt_hi, V)
times, sol = solver_hi.solve(W_true, c_init, Nt=int(T/dt_hi), save_every=2) # snapshots every 0.02
return dict(q=q, dq=dq, k=k, T=T, gamma=gamma, beta=beta, V=V, rho0=rho0,
W_true=W_true, times=times, sol_hi=sol, NH_hi=NH_hi)
truth = generate_truth(0)
q, dq, k = truth['q'], truth['dq'], truth['k']
# shared observation design: same (t_i, q_i) for both models
rng = np.random.default_rng(0)
N_obs = 3000
t_idx = rng.integers(1, len(truth['times']), N_obs) # exclude t=0
q_idx = rng.integers(0, len(q), N_obs)
# --- f-data: also draw momenta p_i and evaluate the full state ---
p_obs = rng.uniform(-3.5, 3.5, N_obs)
B_hi = hermite_eval(truth['NH_hi'], p_obs, truth['beta'])
f_clean = np.einsum('in,in->i', truth['sol_hi'][t_idx, :, q_idx], B_hi)
# --- rho-data: just read c_0 at the same (t_i, q_i); no momentum ---
rho_clean = truth['sol_hi'][t_idx, 0, q_idx]
# common noise-to-signal ratio (noise s.d. / signal s.d.) for the two observables
noise_to_signal = 0.15
sig_f = noise_to_signal*f_clean.std()
sig_rho = noise_to_signal*rho_clean.std()
Y_f = f_clean + sig_f *rng.standard_normal(N_obs)
Y_rho = rho_clean + sig_rho*rng.standard_normal(N_obs)
print(f"snapshots = {len(truth['times'])} (every 0.02 up to T = {truth['T']}), N_obs = {N_obs}")
print(f"f : signal std = {f_clean.std():.4f}, sigma = {sig_f:.4f}, observed values in [{f_clean.min():.3f}, {f_clean.max():.3f}]")
print(f"rho: signal std = {rho_clean.std():.4f}, sigma = {sig_rho:.4f}")
print(f"mass at t=0 = {truth['sol_hi'][0,0].sum()*dq:.10f}, at t=T = {truth['sol_hi'][-1,0].sum()*dq:.10f}")
snapshots = 101 (every 0.02 up to T = 2.0), N_obs = 3000 f : signal std = 0.0269, sigma = 0.0040, observed values in [0.000, 0.113] rho: signal std = 0.0734, sigma = 0.0110 mass at t=0 = 1.0000000000, at t=T = 1.0000000000
3.2.1 Ground truth and synthetic data¶
ts = truth['times']
P_img = np.linspace(-4, 4, 241) # momentum and position grids for the heatmaps
q_img = np.linspace(0, 2*np.pi, 385)
Bp = hermite_eval(truth['NH_hi'], P_img, truth['beta'])
def phase_density(coeff_q): # f(q,p) = sum_n c_n(q) e_n(p) on q_img x P_img
return trig_interp(coeff_q, q_img, axis=1).T @ Bp.T
# ground truth W_0
fig, ax = paper_figure(0.48, 1.9)
ax.plot(q_fine, trig_interp(truth['W_true'], q_fine), color='C0')
set_q_axis(ax); ax.set_ylabel("$W_0(q)$")
plt.show()
# phase-space density at t = 0 and t = T, on a common colour scale
f0 = phase_density(truth['sol_hi'][0])
fT = phase_density(truth['sol_hi'][-1])
f_max = max(f0.max(), fT.max())
for name, f_qp, label in [("f_initial", f0, "$f_{W_0}(0,q,p)$"), ("f_final", fT, "$f_{W_0}(T,q,p)$")]:
fig, ax = paper_figure(0.48, 2.0)
heatmap(ax, f_qp.T, q_img, P_img, 'viridis', label, vmin=0, vmax=f_max)
set_q_axis(ax); ax.set_ylabel("$p$")
save_figure(fig, name)
# density rho(t,q) = c_0(t,q), observed in model (M1), and first Hermite coefficient c_1(t,q), the current (beta = 1)
rho_tq = trig_interp(truth['sol_hi'][:, 0, :], q_img, axis=1)
c1_tq = trig_interp(truth['sol_hi'][:, 1, :], q_img, axis=1)
fig, ax = paper_figure(0.48, 2.0)
heatmap(ax, rho_tq, q_img, ts, 'magma', r"$\rho(t,q)$")
set_q_axis(ax); ax.set_ylabel("$t$")
save_figure(fig, "rho_heatmap")
c1_max = np.abs(c1_tq).max() # colour scale centred at zero
fig, ax = paper_figure(0.48, 2.0)
heatmap(ax, c1_tq, q_img, ts, 'coolwarm', r"$c_1(t,q)$", vmin=-c1_max, vmax=c1_max)
set_q_axis(ax); ax.set_ylabel("$t$")
save_figure(fig, "c1_heatmap")
# density snapshots with the noisy rho-observations falling on them
fig, ax = paper_figure(0.7, 2.2)
for tt, c, label in [(truth['T']/2, 'C0', r'$\rho_{W_0}(T/2,{\cdot})$'), (truth['T'], 'C3', r'$\rho_{W_0}(T,{\cdot})$')]:
it = int(np.argmin(np.abs(truth['times']-tt)))
ax.plot(q_fine, trig_interp(truth['sol_hi'][it, 0], q_fine), color=c, lw=1.4, label=label)
sel = (t_idx == it)
ax.plot(q[q_idx[sel]], Y_rho[sel], '.', color=c, ms=3.5, alpha=0.6)
ax.plot(q_fine, trig_interp(truth['rho0'], q_fine), 'k:', lw=1.2, label=r'$\rho_0$')
set_q_axis(ax); ax.legend()
save_figure(fig, "rho_snapshots_obs")
3.2.2 The prior¶
def build_basis_cos(q, M):
return np.stack([np.cos(m*q) for m in range(1, M+1)], axis=1) # (Nq, M)
def make_scaling(M, tau=1.0, s=1.5):
return np.array([tau/m**s for m in range(1, M+1)]) # prior s.d. of a_k: tau*k^(-s)
def W_from_xi(xi, Phi, scale):
return Phi @ (scale*xi)
# truncation level K = M = 6 and s = alpha + 1 with prior regularity alpha = 1/2 (scale tau = 1)
M, tau, s = 6, 1.0, 1.5
Phi = build_basis_cos(q, M)
scale = make_scaling(M, tau, s)
coef_true = cosine_coefficients(truth['W_true'], q, M)
rng = np.random.default_rng(1)
fig, ax = paper_figure(0.65, 2.2)
for _ in range(6):
ax.plot(q_fine, W_from_xi(rng.standard_normal(M), build_basis_cos(q_fine, M), scale),
lw=0.9, alpha=0.85)
ax.plot(q_fine, trig_interp(truth['W_true'], q_fine), 'k', lw=2, label='$W_0$')
set_q_axis(ax); ax.set_ylabel("$W(q)$"); ax.legend()
save_figure(fig, "prior_draws")
3.2.3 Likelihood and posterior sampling¶
One likelihood evaluation costs exactly one forward PDE solve. The posterior is sampled by the preconditioned Crank–Nicolson (pCN) algorithm in whitened coordinates, with a step size for each mode: of the order of the linearised posterior standard deviation on the modes which the data determine, and equal to one, that is, a fresh draw of the prior, on the others. The steps are set from the information of the data at $W=0$, not at the truth, and every chain starts from a draw of the prior.
Notation: the code variable xi holds the whitened coordinates, written $\theta$ in the paper, and steps holds the proposal standard deviations $\sqrt{2\delta_k}$, so that the proposal is $\theta'_k=\sqrt{1-2\delta_k}\,\theta_k+\sqrt{2\delta_k}\,\xi_k$ with $\xi\sim\mathcal N(0,I_K)$; the Jacobian of the prediction vector is $A$.
# inference-resolution solver (coarser than the truth: N_H = 14, dt = 0.02) and observation basis
NH_inf, dt_inf = 14, 0.02
solver = KineticVFP(q, dq, k, NH_inf, truth['gamma'], truth['beta'], dt_inf, truth['V'])
c_init_inf = np.zeros((NH_inf, len(q))); c_init_inf[0] = truth['rho0']
Nt_inf = int(truth['T']/dt_inf)
B_obs = hermite_eval(NH_inf, p_obs, truth['beta']) # e_n(p_i), for the f-likelihood
def predict_rho(xi):
_, sol = solver.solve(W_from_xi(xi, Phi, scale), c_init_inf, Nt_inf, save_every=1)
return sol[t_idx, 0, q_idx] # rho = c_0 only
def predict_f(xi):
_, sol = solver.solve(W_from_xi(xi, Phi, scale), c_init_inf, Nt_inf, save_every=1)
return np.einsum('in,in->i', sol[t_idx, :, q_idx], B_obs) # full f = sum_n c_n e_n
def loglik_rho(xi): return -0.5*np.sum((Y_rho - predict_rho(xi))**2)/sig_rho**2
def loglik_f(xi): return -0.5*np.sum((Y_f - predict_f(xi))**2)/sig_f**2
def information_diagonal(predict, xi, sigma, h=1e-3):
"""Diagonal of A^T A / sigma^2, with A the Jacobian of the prediction vector at xi (central differences): the
information of the data on each whitened coordinate. Used only to set the pCN step sizes."""
out = np.empty(len(xi))
for m in range(len(xi)):
e = np.zeros(len(xi)); e[m] = h
d = (predict(xi + e) - predict(xi - e))/(2*h)
out[m] = d @ d/sigma**2
return out
def pcn_steps(info, c=1.5):
"""Proposal standard deviations sqrt(2 delta_k) = min(1, c/sqrt(1 + I_k)): of the order of the linearised posterior
s.d. on the modes which the data determine, and one (delta_k = 1/2, a fresh prior draw) on the others."""
return np.minimum(1.0, c/np.sqrt(1.0 + info))
def pcn(loglik, steps, n_iter, seed=1, log_every=None):
"""pCN with a step size delta_k for each mode (the operator-weighted proposal of Law, 2014) in whitened
coordinates xi (theta in the paper): xi'_k = sqrt(1 - 2 delta_k) xi_k + sqrt(2 delta_k) g_k, g ~ N(0, I),
accepted with probability min{1, exp(loglik(xi') - loglik(xi))}, where steps = sqrt(2 delta_k).
The chain starts from a draw of the prior."""
rng = np.random.default_rng(seed)
steps = np.asarray(steps, dtype=float); damp = np.sqrt(1 - steps**2)
xi = rng.standard_normal(len(steps)); ll = loglik(xi)
samples = np.empty((n_iter, len(steps))); ll_chain = np.empty(n_iter); nacc = 0; t0 = time.time()
for it in range(n_iter):
xp = damp*xi + steps*rng.standard_normal(len(steps))
lp = loglik(xp)
if np.log(rng.random()) < lp - ll: xi, ll = xp, lp; nacc += 1
samples[it], ll_chain[it] = xi, ll
if log_every and (it+1) % log_every == 0:
print(f" iter {it+1:5d}/{n_iter} acc={nacc/(it+1):5.1%} ll={ll:9.1f} t={time.time()-t0:5.0f}s")
return samples, ll_chain, nacc/n_iter
def ess(x):
"""Effective sample size of a scalar chain (Geyer's initial positive sequence estimator)."""
x = np.asarray(x, dtype=float) - np.mean(x); n = len(x)
f = np.fft.rfft(x, 2*n); ac = np.fft.irfft(f*np.conj(f))[:n]; ac /= ac[0]
s = 0.0
for t in range(0, n - 1, 2):
pair = ac[t] + ac[t+1]
if pair <= 0: break
s += pair
return n/max(2*s - 1, 1.0)
steps_rho = pcn_steps(information_diagonal(predict_rho, np.zeros(M), sig_rho)) # at W = 0, not at the truth
steps_f = pcn_steps(information_diagonal(predict_f, np.zeros(M), sig_f))
print("pCN steps sqrt(2 delta_k), model (M1):", np.round(steps_rho, 3))
print("pCN steps sqrt(2 delta_k), model (M2):", np.round(steps_f, 3))
_t = time.time(); loglik_rho(np.zeros(M))
print(f"one likelihood evaluation: {time.time()-_t:.3f}s; target plateau -N/2 = {-N_obs/2:.0f}")
pCN steps sqrt(2 delta_k), model (M1): [0.025 0.113 1. 1. 1. 1. ] pCN steps sqrt(2 delta_k), model (M2): [0.041 0.181 1. 1. 1. 1. ] one likelihood evaluation: 0.035s; target plateau -N/2 = -1500
n_iter = 6000; burn = n_iter//5
samples_rho, ll_rho, acc_rho = pcn(loglik_rho, steps_rho, n_iter=n_iter, seed=1, log_every=1500)
samples_f, ll_f, acc_f = pcn(loglik_f, steps_f, n_iter=n_iter, seed=1, log_every=1500)
post = {'rho': samples_rho[burn:], 'f': samples_f[burn:]}
acc = {'rho': acc_rho, 'f': acc_f}; traces = {'rho': ll_rho, 'f': ll_f}
coef_mean, coef_sd, W_post, rhoT_post, errW = {}, {}, {}, {}, {}
for model, name, col, mk in MODELS:
ch = post[model]*scale
coef_mean[model], coef_sd[model] = ch.mean(0), ch.std(0)
W_post[model] = W_from_xi(post[model].mean(0), Phi, scale) # posterior mean on the grid
_, sol_ = solver.solve(W_post[model], c_init_inf, Nt_inf, save_every=1); rhoT_post[model] = sol_[-1, 0]
errW[model] = np.sqrt(torus_integral((W_post[model] - truth['W_true'])**2, dq))
err_rhoT = np.sqrt(torus_integral((rhoT_post[model] - truth['sol_hi'][-1, 0])**2, dq))
print(f"model {name}: acceptance {acc[model]:.1%}; effective sample sizes of a_1, ..., a_6: "
f"{[int(ess(post[model][:, m])) for m in range(M)]} of {n_iter - burn}")
print(f" ||W_N - W_0||_L2 = {errW[model]:.4f}; ||rho_W_N(T) - rho_W_0(T)||_L2 = {err_rhoT:.1e} "
f"(root-mean-square {err_rhoT/np.sqrt(2*np.pi):.1e}); mean log-likelihood after burn-in "
f"{traces[model][burn:].mean():.0f}")
iter 1500/6000 acc=32.0% ll= -1488.3 t= 53s
iter 3000/6000 acc=31.7% ll= -1488.9 t= 107s
iter 4500/6000 acc=32.4% ll= -1489.5 t= 163s
iter 6000/6000 acc=32.0% ll= -1489.3 t= 216s
iter 1500/6000 acc=34.1% ll= -1535.0 t= 52s
iter 3000/6000 acc=33.6% ll= -1534.4 t= 107s
iter 4500/6000 acc=34.5% ll= -1536.3 t= 160s
iter 6000/6000 acc=34.2% ll= -1535.9 t= 211s
model (M1): acceptance 32.0%; effective sample sizes of a_1, ..., a_6: [624, 341, 518, 829, 634, 725] of 4800
||W_N - W_0||_L2 = 0.2349; ||rho_W_N(T) - rho_W_0(T)||_L2 = 7.0e-04 (root-mean-square 2.8e-04); mean log-likelihood after burn-in -1490
model (M2): acceptance 34.2%; effective sample sizes of a_1, ..., a_6: [512, 433, 507, 934, 694, 882] of 4800
||W_N - W_0||_L2 = 0.2609; ||rho_W_N(T) - rho_W_0(T)||_L2 = 1.4e-03 (root-mean-square 5.7e-04); mean log-likelihood after burn-in -1536
rng_p = np.random.default_rng(7)
Phi_fine = build_basis_cos(q_fine, M)
# posterior draws, truth and posterior mean, for each model
for model, name, col, mk in MODELS:
fig, ax = paper_figure(0.48, 2.1)
plot_reconstruction(ax, post[model], Phi_fine, scale, truth['W_true'], rng_p)
ax.set_title(f"model {name}", fontsize=8)
save_figure(fig, f"W_posterior_{model}")
# cosine coefficients: posterior mean ± s.d. for both models against the truth
fig, ax = paper_figure(0.48, 2.1)
plot_coefficients_models(ax, coef_mean, coef_sd, coef_true)
save_figure(fig, "coeffs")
# log-likelihood traces
fig, ax = paper_figure(0.48, 2.1)
plot_traces(ax, traces, burn, N_obs, r"$\ell_N$")
save_figure(fig, "ll_trace")
print(" " + " ".join(f" a{m}" for m in range(1, M+1)))
print("truth :", " ".join(f"{v:+.3f}" for v in coef_true))
for model, name, col, mk in MODELS:
print(f"{name} mean:", " ".join(f"{v:+.3f}" for v in coef_mean[model]))
print(f"{name} s.d.:", " ".join(f"{v:+.3f}" for v in coef_sd[model]))
print("prior s.d.:", " ".join(f"{v:+.3f}" for v in scale))
a1 a2 a3 a4 a5 a6 truth : -1.000 +0.500 -0.250 +0.000 +0.000 +0.000 (M1) mean: -0.997 +0.519 -0.119 -0.006 +0.008 -0.001 (M1) s.d.: +0.014 +0.036 +0.155 +0.128 +0.088 +0.066 (M2) mean: -0.984 +0.541 -0.110 -0.005 +0.008 -0.000 (M2) s.d.: +0.023 +0.054 +0.169 +0.126 +0.088 +0.065 prior s.d.: +1.000 +0.354 +0.192 +0.125 +0.089 +0.068
3.3.2 Identifiability and the linearised posterior¶
Linearising the forward map at the truth: the SVD of the Jacobian predicts, mode by mode, which Fourier frequencies of $W$ the data identify, for both models. This uses the truth and serves as a diagnostic of the experiment; it plays no part in the sampler.
# Linearise the forward map at W_true and read off the identifiability structure, for both models.
xi_true = coef_true/scale # the truth in whitened coordinates
def jacobian(predict, xi0, h=1e-3):
base = predict(xi0); J = np.zeros((len(base), len(xi0)))
for m in range(len(xi0)):
e = np.zeros(len(xi0)); e[m] = h
J[:, m] = (predict(xi0 + e) - predict(xi0 - e))/(2*h)
return J
sig = {'rho': sig_rho, 'f': sig_f}
S, info = {}, {}
for model, name, col, mk in MODELS:
U_, S[model], Vt = np.linalg.svd(jacobian(predict_rho if model == 'rho' else predict_f, xi_true), full_matrices=False)
info[model] = (S[model]/sig[model])**2 # per-mode information I_k = (sigma_k/sigma)^2
dom = [int(np.argmax(np.abs(v))) + 1 for v in Vt]
print(f"model {name}: singular values {np.array2string(S[model], formatter={'float_kind': lambda v: f'{v:.2e}'})}")
print(f" dominant mode of each singular direction {dom}, weights "
f"{np.round([abs(v[d - 1]) for v, d in zip(Vt, dom)], 2)}")
print(f" information I_k {np.array2string(info[model], formatter={'float_kind': lambda v: f'{v:.2e}'})}")
print("ratio of the singular values to the largest, (M1) / (M2):", np.round((S['rho']/S['rho'][0])/(S['f']/S['f'][0]), 3))
print("information ratio I^rho_k / I^f_k:", np.round(info['rho']/info['f'], 2))
fig, ax = paper_figure(0.48, 2.1)
for model, name, col, mk in MODELS:
ax.semilogy(np.arange(1, M+1), info[model], mk + '-', color=col, ms=3.5, label=f'model {name}')
ax.axhline(1.0, color='k', ls='--', lw=1, label='prior precision')
ax.set_xticks(np.arange(1, M+1)); ax.set_xlabel("mode $k$"); ax.set_ylabel(r"information $\mathscr{I}_k$")
ax.legend()
save_figure(fig, "info_ladder")
model (M1): singular values [7.97e-01 1.13e-01 8.73e-03 5.86e-04 5.51e-05 3.38e-06]
dominant mode of each singular direction [1, 2, 3, 4, 5, 6], weights [1. 1. 1. 1. 1. 1.]
information I_k [5.24e+03 1.06e+02 6.28e-01 2.84e-03 2.51e-05 9.45e-08]
model (M2): singular values [1.74e-01 2.74e-02 2.05e-03 1.32e-04 1.28e-05 7.43e-07]
dominant mode of each singular direction [1, 2, 3, 4, 5, 6], weights [1. 1. 1. 1. 1. 1.]
information I_k [1.86e+03 4.60e+01 2.57e-01 1.06e-03 9.98e-06 3.38e-08]
ratio of the singular values to the largest, (M1) / (M2): [1. 0.906 0.932 0.975 0.946 0.997]
information ratio I^rho_k / I^f_k: [2.81 2.31 2.44 2.68 2.52 2.79]
# fine-solver "truth" for the harder potential, observed in model (M2) at its noise level
W_hard = 0.8*np.cos(q) - 0.6*np.cos(2*q) + 0.4*np.cos(3*q) - 0.25*np.cos(4*q)
truth_h = generate_truth(W_true=W_hard)
# observations: same type of design, new draws
rngh = np.random.default_rng(7)
Nh = 3000
ti = rngh.integers(1, len(truth_h['times']), Nh); qi = rngh.integers(0, len(q), Nh)
pi_h = rngh.uniform(-3.5, 3.5, Nh)
fH = np.einsum('in,in->i', truth_h['sol_hi'][ti, :, qi], hermite_eval(truth_h['NH_hi'], pi_h, truth['beta']))
YH = fH + sig_f*rngh.standard_normal(Nh)
# inference at the coarse resolution, with a wider prior, K = 8
Mh = 8
Phi_h = build_basis_cos(q, Mh); scale_h = make_scaling(Mh, 1.0, 1.5)
B_h = hermite_eval(NH_inf, pi_h, truth['beta'])
coef_true_h = cosine_coefficients(W_hard, q, Mh)
def predict_h(xi):
_, s_ = solver.solve(W_from_xi(xi, Phi_h, scale_h), c_init_inf, Nt_inf, save_every=1)
return np.einsum('in,in->i', s_[ti, :, qi], B_h)
def loglik_h(xi):
return -0.5*np.sum((YH - predict_h(xi))**2)/sig_f**2
steps_h = pcn_steps(information_diagonal(predict_h, np.zeros(Mh), sig_f))
n_h = 6000
samp_h, _, acc_h = pcn(loglik_h, steps_h, n_iter=n_h, seed=3, log_every=1500)
print(f" acceptance {acc_h:.1%}, steps {np.round(steps_h, 3)}")
post_h = samp_h[n_h//5:]*scale_h
print(" effective sample sizes:", [int(ess(post_h[:, m])) for m in range(Mh)])
cmh, csh = post_h.mean(0), post_h.std(0)
print(f"\n true coeffs: {np.round(coef_true_h,3)}")
print(f" post coeffs: {np.round(cmh,3)} +- {np.round(csh,3)}")
fig, ax = paper_figure(0.48, 2.1)
ax.plot(q_fine, trig_interp(W_hard, q_fine), 'k', lw=1.4, label=r'$W_{\mathrm{hard}}$')
ax.plot(q_fine, build_basis_cos(q_fine, Mh) @ cmh, '--', color='C3', lw=1.4, label=r'$\widetilde{W}_N$')
set_q_axis(ax); ax.legend(loc='lower left')
save_figure(fig, "W_hard_recon")
fig, ax = paper_figure(0.48, 2.1)
plot_coefficients(ax, cmh, csh, coef_true_h)
save_figure(fig, "W_hard_coeffs")
iter 1500/6000 acc=21.7% ll= -1435.7 t= 52s iter 3000/6000 acc=20.5% ll= -1436.7 t= 101s iter 4500/6000 acc=20.3% ll= -1435.6 t= 135s iter 6000/6000 acc=19.7% ll= -1436.3 t= 168s acceptance 19.7%, steps [0.04 0.187 1. 1. 1. 1. 1. 1. ] effective sample sizes: [242, 360, 352, 377, 369, 262, 464, 401] true coeffs: [ 0.8 -0.6 0.4 -0.25 0. 0. 0. 0. ] post coeffs: [ 0.79 -0.577 0.211 -0.004 0.005 0.005 -0. -0.001] +- [0.031 0.037 0.142 0.12 0.089 0.069 0.052 0.043]
The fully parametric limit¶
# sweep the truncation level K (= Mtry) from a few modes up to the fully parametric limit, for both models
def run_pcn_M(model, Mtry, n_iter=4000, seed=1, s_prior=1.5, tau_prior=1.0):
"""Self-contained pCN at truncation level K = Mtry (leaves the globals of the K = 6 runs untouched)."""
Phi_M = build_basis_cos(q, Mtry)
scale_M = make_scaling(Mtry, tau_prior, s_prior)
if model == 'rho':
Y_, sig_, obs = Y_rho, sig_rho, (lambda sol: sol[t_idx, 0, q_idx])
else:
Y_, sig_, obs = Y_f, sig_f, (lambda sol: np.einsum('in,in->i', sol[t_idx, :, q_idx], B_obs))
def predict(xi):
return obs(solver.solve(Phi_M @ (scale_M*xi), c_init_inf, Nt_inf, save_every=1)[1])
def loglik(xi):
return -0.5*np.sum((Y_ - predict(xi))**2)/sig_**2
steps_M = pcn_steps(information_diagonal(predict, np.zeros(Mtry), sig_))
samples, _, acc_M = pcn(loglik, steps_M, n_iter, seed=seed)
return dict(samples=samples, scale=scale_M, Phi=Phi_M, acc=acc_M, n_iter=n_iter)
M_full = len(q)//2 - 1 # every cosine mode the Nq-point grid resolves, except the Nyquist mode
M_grid = [3, 6, 12, M_full]
print(f"fully parametric truncation for Nq={len(q)}: K = {M_full}\n")
sweeps = {'rho': {}, 'f': {}}
t0 = time.time()
for model, name, col, mk in MODELS:
for Mtry in M_grid:
res = run_pcn_M(model, Mtry)
post_M = res['samples'][res['n_iter']//5:] # discard the first fifth as burn-in
res['post'] = post_M
res['errW'] = np.sqrt(torus_integral((res['Phi'] @ (res['scale']*post_M.mean(0)) - truth['W_true'])**2, dq))
sweeps[model][Mtry] = res
print(f" model {name} K={Mtry:2d} acc={res['acc']:5.1%} ||W_N - W_0||_L2 = {res['errW']:.4f} "
f"min ESS = {min(int(ess(post_M[:, m])) for m in range(Mtry))}")
print(f"\nsweep wall-clock: {time.time()-t0:.0f}s")
plot_sweep_models(sweeps, truth['W_true'], "Msweep")
fully parametric truncation for Nq=48: K = 23 model (M1) K= 3 acc=31.6% ||W_N - W_0||_L2 = 0.2065 min ESS = 265 model (M1) K= 6 acc=32.2% ||W_N - W_0||_L2 = 0.2308 min ESS = 275 model (M1) K=12 acc=31.6% ||W_N - W_0||_L2 = 0.2206 min ESS = 201 model (M1) K=23 acc=31.7% ||W_N - W_0||_L2 = 0.2167 min ESS = 114 model (M2) K= 3 acc=32.2% ||W_N - W_0||_L2 = 0.2467 min ESS = 219 model (M2) K= 6 acc=33.9% ||W_N - W_0||_L2 = 0.2587 min ESS = 296 model (M2) K=12 acc=32.7% ||W_N - W_0||_L2 = 0.2528 min ESS = 243 model (M2) K=23 acc=34.5% ||W_N - W_0||_L2 = 0.2726 min ESS = 245 sweep wall-clock: 699s
Linearised posterior and posterior marginals (Section 3.3.2)¶
The linearisation at the truth at the fully parametric truncation $K=23$, for both models, computed here because the empirical shrinkage uses the pCN chains at $K=23$ of the sweep above.
# linearised posterior per mode at the fully parametric truncation, for both models
Phi_full = build_basis_cos(q, M_full)
scale_full = make_scaling(M_full, 1.0, 1.5)
coef_true_full = cosine_coefficients(truth['W_true'], q, M_full)
xi_true_full = coef_true_full / scale_full
def predict_rho_full(xi):
_, sol = solver.solve(Phi_full @ (scale_full*xi), c_init_inf, Nt_inf, save_every=1)
return sol[t_idx, 0, q_idx]
def predict_f_full(xi):
_, sol = solver.solve(Phi_full @ (scale_full*xi), c_init_inf, Nt_inf, save_every=1)
return np.einsum('in,in->i', sol[t_idx, :, q_idx], B_obs)
def linearised_posterior(predict, Y, sig_):
"""Shrinkage S_k, posterior s.d. and posterior mean in whitened coordinates of the linearised posterior at the
truth: the forward map linearised at the truth (Gauss-Newton expansion of the log-likelihood) combined with the
N(0, I) prior on the whitened coordinates."""
h = 1e-3; F0 = predict(xi_true_full); J = np.zeros((len(F0), M_full))
for m in range(M_full):
e = np.zeros(M_full); e[m] = h
J[:, m] = (predict(xi_true_full + e) - predict(xi_true_full - e)) / (2*h)
Sig = np.linalg.inv(np.eye(M_full) + J.T @ J / sig_**2)
mean = xi_true_full + Sig @ (J.T @ (Y - F0)/sig_**2 - xi_true_full)
return 1 - np.diag(Sig), np.sqrt(np.clip(np.diag(Sig), 0, None)), mean
lin_post = {}
for model, pred_full, Y_ in (('rho', predict_rho_full, Y_rho), ('f', predict_f_full, Y_f)):
shrink_, sd_w, mean_w = linearised_posterior(pred_full, Y_, sig_rho if model == 'rho' else sig_f)
lin_post[model] = dict(shrink=shrink_, sd=scale_full*sd_w, mean=scale_full*mean_w)
prior_sd = scale_full
# prior against linearised posterior marginals, mode by mode (first 12 modes), for both models
plot_marginals(prior_sd, lin_post, coef_true_full, name="marginals")
# linearised shrinkage over all modes, with the empirical shrinkage of the pCN chains at K = 23
modes = np.arange(1, M_full+1)
emp_shrink = {model: 1 - ((sweeps[model][M_full]['post']*scale_full).std(0)/prior_sd)**2 for model in sweeps}
fig, ax = paper_figure(0.48, 2.1)
for model, name, col, mk in MODELS:
ax.plot(modes, lin_post[model]['shrink'], mk + '-', color=col, ms=2.8, lw=1, label=f'linearised, {name}')
ax.plot(modes, emp_shrink[model], mk, color=col, ms=4.2, mfc='none', mew=0.8, label=f'pCN chain, {name}')
ax.axhline(0, color='k', lw=0.5)
ax.set_xticks([1, 5, 10, 15, 20, 23])
ax.set_xlabel("mode $k$"); ax.set_ylabel(r"$\mathscr{S}_k$")
ax.legend(loc='upper right', fontsize=7)
save_figure(fig, "shrinkage")
fmt = {'float_kind': lambda v: f'{v:9.2e}'}
print("k :", " ".join(f"{m:9d}" for m in range(1, 9)))
for model, name, col, mk in MODELS:
print(f"S_k linearised, {name} :", np.array2string(lin_post[model]['shrink'][:8], formatter=fmt, max_line_width=200)[1:-1])
print(f"S_k pCN chain K=23, {name} :", np.array2string(emp_shrink[model][:8], formatter=fmt, max_line_width=200)[1:-1])
print(f"linearised s.d. a_k, {name}:", np.array2string(lin_post[model]['sd'][:8], formatter=fmt, max_line_width=200)[1:-1])
print(f"linearised mean a_k, {name}:", np.array2string(lin_post[model]['mean'][:8], formatter=fmt, max_line_width=200)[1:-1])
k : 1 2 3 4 5 6 7 8 S_k linearised, (M1) : 1.00e+00 9.90e-01 3.86e-01 3.12e-03 2.84e-05 1.23e-07 8.51e-10 9.50e-12 S_k pCN chain K=23, (M1) : 1.00e+00 9.91e-01 3.85e-01 -4.92e-02 1.79e-02 -6.89e-04 1.01e-01 2.92e-02 linearised s.d. a_k, (M1): 1.40e-02 3.46e-02 1.51e-01 1.25e-01 8.94e-02 6.80e-02 5.40e-02 4.42e-02 linearised mean a_k, (M1): -9.98e-01 5.19e-01 -1.35e-01 -7.72e-03 -7.29e-04 -2.63e-05 -2.24e-06 -3.25e-07 S_k linearised, (M2) : 9.99e-01 9.79e-01 2.05e-01 1.11e-03 1.06e-05 3.96e-08 4.15e-10 4.85e-12 S_k pCN chain K=23, (M2) : 9.99e-01 9.77e-01 2.70e-01 -3.28e-02 5.11e-02 -1.06e-02 -1.63e-02 -4.19e-02 linearised s.d. a_k, (M2): 2.36e-02 5.16e-02 1.72e-01 1.25e-01 8.94e-02 6.80e-02 5.40e-02 4.42e-02 linearised mean a_k, (M2): -9.87e-01 5.39e-01 -1.27e-01 -3.93e-03 -3.39e-04 -2.55e-06 -7.72e-07 -5.79e-08
3.4 Posterior contraction as the sample size grows¶
Both measurement models, with the prior of Section 3.2.2 ($K=6$, $\alpha=1/2$) kept fixed and the designs and noise levels of Section 3.2.1. For each of $R=8$ independent sequences of observations, the posterior given the first $N$ observations is sampled, for $N=500\cdot2^j$, $j=0,\dots,7$, by $C=2$ independent pCN chains of $3000$ iterations. Recorded: the posterior root-mean-square distance $r_N(\mathcal G)$ to the truth of the forward quantity in the design norm, and those of $\pi_2W$ (modes 1–2) and of $W$ in $L^2$, averaged over the sequences (root mean square), with the range over the sequences; their linearised prediction at the truth, averaged over the noise; the fitted exponents, with their jackknife standard errors over the sequences; and the diagnostics of the chains: acceptance rates, effective sample sizes, split-$\hat R$ and Monte Carlo standard errors.
The long run of this section advances all chains of a given $N$ together, with the batched version of the solver defined in the next cell.
# Batched solver for the long run of Section 3.4: the same Strang splitting with exact substeps as
# KineticVFP, advancing B interactions at once (c of shape (B, N_H, N_q)) on real FFTs, which amortises the
# per-step overhead over many chains; it agrees with KineticVFP to rounding error (check below).
def force_kick_batch(c, A, tau, beta):
"""force_kick for a batch, c (B, NH, Nq), A (B, Nq): the j-th term of the finite Taylor sum lives on the levels n >= j."""
NH = c.shape[1]; sb = np.sqrt(beta*np.arange(NH))
out = c.copy(); term = c
for j in range(1, NH):
term = (tau/j)*sb[j:, None]*A[:, None, :]*term[:, :-1]
out[:, j:] += term
return out
class KineticVFPBatch:
def __init__(self, q, dq, k, NH, gamma, beta, dt, V):
self.q, self.dq, self.NH, self.gamma, self.beta, self.dt = q, dq, NH, gamma, beta, dt
self.Nq = len(q); self.kr = np.abs(k[:self.Nq//2 + 1]) # wavenumbers 0, ..., Nq/2 of the real FFT
self.dV = np.real(np.fft.ifft(1j*k*np.fft.fft(V)))
_, self.Er = build_linear_exponentials(self.kr, NH, gamma, beta, dt) # exp(dt L_k), (Nq/2+1, NH, NH)
def force_field(self, rho, W_hat):
return -self.dV - np.fft.irfft(1j*self.kr*self.dq*W_hat*np.fft.rfft(rho, axis=-1), n=self.Nq, axis=-1)
def linear_step(self, c):
chat = np.matmul(self.Er, np.fft.rfft(c, axis=-1).transpose(2, 1, 0)).transpose(2, 1, 0)
return np.fft.irfft(chat, n=self.Nq, axis=-1)
def solve(self, W, c_init, Nt, save_every=1):
"""Solutions for the interactions W (B, Nq) from the common initial coefficients c_init (NH, Nq): (Ns, B, NH, Nq)."""
W = np.atleast_2d(W); W_hat = np.fft.rfft(W, axis=-1); dt = self.dt
c = np.broadcast_to(c_init, (W.shape[0],) + c_init.shape).copy()
saved, times = [c.copy()], [0.0]
for nstep in range(Nt):
c = force_kick_batch(c, self.force_field(c[:, 0], W_hat), dt/2, self.beta)
c = self.linear_step(c)
c = force_kick_batch(c, self.force_field(c[:, 0], W_hat), dt/2, self.beta)
if (nstep+1) % save_every == 0:
saved.append(c.copy()); times.append((nstep+1)*dt)
return np.array(times), np.array(saved)
def split_rhat(x):
"""Split-R-hat of the chains x of shape (C, n) [Gelman et al., Bayesian Data Analysis, 3rd ed., Sec. 11.4]."""
n2 = x.shape[1]//2
h = np.concatenate([x[:, :n2], x[:, n2:2*n2]])
W_, B_ = h.var(axis=1, ddof=1).mean(), n2*h.mean(axis=1).var(ddof=1)
return np.sqrt(((n2 - 1)/n2*W_ + B_/n2)/W_)
solver_b = KineticVFPBatch(q, dq, k, NH_inf, truth['gamma'], truth['beta'], dt_inf, truth['V'])
xis_chk = np.random.default_rng(5).standard_normal((32, M))
Ws_chk = xis_chk @ (scale[:, None]*Phi.T)
t_b = time.time(); _, sol_b = solver_b.solve(Ws_chk, c_init_inf, Nt_inf); t_b = time.time() - t_b
t_s = time.time(); sol_s = np.array([solver.solve(W_, c_init_inf, Nt_inf)[1] for W_ in Ws_chk]); t_s = time.time() - t_s
print(f"32 interactions: max|batched - sequential| = {np.abs(sol_b.transpose(1, 0, 2, 3) - sol_s).max():.1e}; "
f"{t_b:.2f}s batched against {t_s:.2f}s sequential")
32 interactions: max|batched - sequential| = 1.4e-15; 0.16s batched against 0.71s sequential
# R independent sequences of observations for each model, drawn from the designs of Section 3.2.1 at its
# noise levels; for each sequence, the posterior given its first N observations is sampled, for
# N = 500*2^j, j = 0, ..., 7, by C independent pCN chains. Along a sequence, each chain starts, for each N, from its
# own last state for the previous N (at N = 500, the C chains start from independent draws of the prior), as the
# posterior concentrates by a factor of order 1/sqrt(2) from one N to the next. All R x 2 x C chains of a given N
# advance together, with one batched forward solve per iteration (KineticVFPBatch). Averaging over the R sequences
# estimates the expectation over the data, which the linearised prediction of the next cell computes; the C chains
# of each posterior give the between-chain diagnostics.
N_grid = [500*2**j for j in range(8)]
R, C = 8, 2
n_iter_rate = 3000; burn_rate = n_iter_rate//5
models = ('rho', 'f')
# design norms over the whole design: the 100 positive snapshot times x 48 grid points and, for f,
# the uniform momentum design on [-3.5, 3.5] (Gauss-Legendre quadrature of the products e_n e_m)
p_gl, w_gl = np.polynomial.legendre.leggauss(40); p_gl = 3.5*p_gl; w_gl = w_gl/2
B_gl = hermite_eval(NH_inf, p_gl, truth['beta'])
G_p = B_gl.T @ (w_gl[:, None]*B_gl)
def forward_fields(xi):
_, sol = solver.solve(W_from_xi(xi, Phi, scale), c_init_inf, Nt_inf, save_every=1)
return sol[1:] # (100, NH, Nq)
fields_0 = forward_fields(xi_true)
def dist2_rho(sol): return np.mean((sol[:, 0, :] - fields_0[:, 0, :])**2)
def dist2_f(sol):
d = (sol - fields_0).transpose(1, 0, 2).reshape(NH_inf, -1) # (NH, 100 x Nq)
return np.mean(np.sum(d*(G_p @ d), axis=0))
dist2 = {'rho': dist2_rho, 'f': dist2_f}
def observation_sequence(seed, N_max):
rng_seq = np.random.default_rng(seed)
t_s = rng_seq.integers(1, len(truth['times']), N_max) # positive snapshot times
q_s = rng_seq.integers(0, len(q), N_max)
p_s = rng_seq.uniform(-3.5, 3.5, N_max)
Yf = np.einsum('in,in->i', truth['sol_hi'][t_s, :, q_s],
hermite_eval(truth['NH_hi'], p_s, truth['beta'])) + sig_f*rng_seq.standard_normal(N_max)
Yr = truth['sol_hi'][t_s, 0, q_s] + sig_rho*rng_seq.standard_normal(N_max)
return dict(t=t_s, q=q_s, B=hermite_eval(NH_inf, p_s, truth['beta']), Yf=Yf, Yr=Yr)
seqs = [observation_sequence(2026 + r, N_grid[-1]) for r in range(R)]
chains = [(model, r, c) for model in models for r in range(R) for c in range(C)]
state = {ch: np.random.default_rng(100*(ch[2] + 1) + ch[1]).standard_normal(M) for ch in chains} # prior draws
def likelihood_setup(model, r, N):
"""Data, noise level and predicted observations (from a solution array) of the first N observations."""
seq = seqs[r]; t_, q_ = seq['t'][:N], seq['q'][:N]
if model == 'rho':
return seq['Yr'][:N], sig_rho, lambda sol: sol[t_, 0, q_]
B_ = seq['B'][:N]
return seq['Yf'][:N], sig_f, lambda sol: np.einsum('in,in->i', sol[t_, :, q_], B_)
# runs[model][r][N]: posterior means of the squared distances, and the diagnostics of the C chains
runs = {model: [dict() for _ in range(R)] for model in models}
t0 = time.time()
for N in N_grid:
setups = {(model, r): likelihood_setup(model, r, N) for model in models for r in range(R)}
steps_, rngs = [], []
for model, r, c in chains:
Y_, sig_, pred = setups[(model, r)]
if c == 0: # step sizes from the information at W = 0
st = pcn_steps(information_diagonal(lambda xi: pred(solver.solve(W_from_xi(xi, Phi, scale), c_init_inf,
Nt_inf, save_every=1)[1]),
np.zeros(M), sig_))
steps_.append(st); rngs.append(np.random.default_rng([1000*r + N, c, models.index(model)]))
steps_ = np.array(steps_); damp = np.sqrt(1 - steps_**2)
nb_ = len(chains)
def loglik_batch(xis):
"""Log-likelihoods of the states xis (B, M) of all chains, and the solutions, from one batched solve."""
sols = solver_b.solve(xis @ (scale[:, None]*Phi.T), c_init_inf, Nt_inf)[1] # (Ns, B, NH, Nq)
ll_ = np.empty(nb_)
for b, (model, r, c) in enumerate(chains):
Y_, sig_, pred = setups[(model, r)]
ll_[b] = -0.5*np.sum((Y_ - pred(sols[:, b]))**2)/sig_**2
return ll_, sols
xi = np.array([state[ch] for ch in chains])
ll, sols = loglik_batch(xi)
d2 = np.array([dist2[ch[0]](sols[1:, b]) for b, ch in enumerate(chains)])
rec_xi = np.empty((nb_, n_iter_rate - burn_rate, M)); rec_d2 = np.empty((nb_, n_iter_rate - burn_rate))
n_acc = np.zeros(nb_)
for it in range(n_iter_rate):
xp = damp*xi + steps_*np.array([g.standard_normal(M) for g in rngs])
lp, sols = loglik_batch(xp)
for b, g in enumerate(rngs):
if np.log(g.random()) < lp[b] - ll[b]:
xi[b], ll[b], d2[b] = xp[b], lp[b], dist2[chains[b][0]](sols[1:, b]); n_acc[b] += 1
if it >= burn_rate:
rec_xi[:, it - burn_rate], rec_d2[:, it - burn_rate] = xi, d2
for b, ch in enumerate(chains):
state[ch] = xi[b].copy()
# summaries over the C chains of each posterior
for model in models:
for r in range(R):
idx = [b for b, ch in enumerate(chains) if ch[0] == model and ch[1] == r]
a_err = rec_xi[idx]*scale - coef_true # (C, n, M)
fun = {'fwd2': rec_d2[idx], 'pi2_2': np.pi*np.sum(a_err[..., :2]**2, -1),
'W2': np.pi*np.sum(a_err**2, -1)}
ess_of = lambda x: sum(ess(xc) for xc in x) # summed over the chains
out = {key: val.mean() for key, val in fun.items()}
out['mcse'] = {key: val.std()/np.sqrt(ess_of(val)) for key, val in fun.items()}
out['acc'] = n_acc[idx]/n_iter_rate
out['ess'] = min(ess_of(rec_xi[idx][..., m]) for m in range(2)) # of a_1 and a_2
out['rhat'] = max([split_rhat(rec_xi[idx][..., m]) for m in range(2)]
+ [split_rhat(fun[key]) for key in fun])
runs[model][r][N] = out
print(f"N = {N:5d} done [{time.time() - t0:.0f}s]")
# posterior root-mean-square distances, averaged over the R sequences of data, and their Monte Carlo errors
def average(model, key, rs=None):
rs = range(R) if rs is None else rs
return np.array([np.sqrt(np.mean([runs[model][r][N][key] for r in rs])) for N in N_grid])
def spread(model, key):
vals = np.array([[np.sqrt(runs[model][r][N][key]) for r in range(R)] for N in N_grid])
return vals.min(1), vals.max(1)
def rel_mcse(model, key):
"""Monte Carlo standard error of r_N relative to r_N (delta method), at each N."""
return np.array([0.5*np.sqrt(sum(runs[model][r][N]['mcse'][key]**2 for r in range(R)))
/ sum(runs[model][r][N][key] for r in range(R)) for N in N_grid])
rates = {model: {key: average(model, key) for key in ('fwd2', 'pi2_2', 'W2')} for model in models}
n_kept = C*(n_iter_rate - burn_rate)
for model, name, sig in (('rho', '(M1)', sig_rho), ('f', '(M2)', sig_f)):
acc = np.concatenate([runs[model][r][N]['acc'] for r in range(R) for N in N_grid])
print(f"{name}: r_N(G)/sigma = " + " ".join(f"{v:.2e}" for v in rates[model]['fwd2']/sig))
print(f" r_N(pi_2 W) = " + " ".join(f"{v:.4f}" for v in rates[model]['pi2_2']))
print(f" r_N(W) = " + " ".join(f"{v:.3f}" for v in rates[model]['W2']))
print(f" acceptance {acc.min():.0%}-{acc.max():.0%}, min ESS of a_1, a_2: "
f"{min(int(runs[model][r][N]['ess']) for r in range(R) for N in N_grid)} of {n_kept}, max split-R-hat: "
f"{max(runs[model][r][N]['rhat'] for r in range(R) for N in N_grid):.3f}")
print(" relative Monte Carlo error of r_N(G): " + " ".join(f"{v:.1%}" for v in rel_mcse(model, 'fwd2'))
+ "; of r_N(pi_2 W): max " + f"{rel_mcse(model, 'pi2_2').max():.1%}")
N = 500 done [688s]
N = 1000 done [1459s]
N = 2000 done [2217s]
N = 4000 done [2928s]
N = 8000 done [3697s]
N = 16000 done [4555s]
N = 32000 done [5498s]
N = 64000 done [6589s]
(M1): r_N(G)/sigma = 8.67e-02 6.23e-02 4.48e-02 3.29e-02 2.53e-02 1.78e-02 1.32e-02 9.04e-03
r_N(pi_2 W) = 0.2001 0.1577 0.0944 0.0774 0.0559 0.0401 0.0257 0.0162
r_N(W) = 0.669 0.637 0.586 0.509 0.459 0.382 0.368 0.339
acceptance 20%-43%, min ESS of a_1, a_2: 225 of 4800, max split-R-hat: 1.022
relative Monte Carlo error of r_N(G): 0.6% 0.6% 0.5% 0.6% 0.6% 0.6% 0.6% 0.6%; of r_N(pi_2 W): max 1.0%
(M2): r_N(G)/sigma = 8.34e-02 6.36e-02 4.37e-02 3.71e-02 2.48e-02 1.74e-02 1.31e-02 9.49e-03
r_N(pi_2 W) = 0.3109 0.2583 0.1768 0.1527 0.0957 0.0676 0.0509 0.0328
r_N(W) = 0.702 0.656 0.620 0.577 0.501 0.472 0.391 0.362
acceptance 21%-42%, min ESS of a_1, a_2: 202 of 4800, max split-R-hat: 1.025
relative Monte Carlo error of r_N(G): 0.6% 0.6% 0.6% 0.6% 0.6% 0.6% 0.6% 0.6%; of r_N(pi_2 W): max 1.0%
# Linearised prediction, averaged over the noise. With A the Jacobian of the forward fields at the
# truth and G its Gram matrix per observation in the design norm, the linearised posterior given N
# observations has covariance Sigma_N = (I + N G/sigma^2)^{-1} in whitened coordinates, and
# E (xi - xi_0)(xi - xi_0)^T = Sigma_N + Sigma_N (N G/sigma^2) Sigma_N + Sigma_N xi_0 xi_0^T Sigma_N,
# spread + noise in the posterior mean + bias from the prior, under posterior and noise.
h = 1e-3
dfields = np.array([(forward_fields(xi_true + h*e) - forward_fields(xi_true - h*e))/(2*h)
for e in np.eye(M)]) # (M, 100, NH, Nq)
n_design = dfields.shape[1]*dfields.shape[3]
G_rho = np.einsum('atq,btq->ab', dfields[:, :, 0, :], dfields[:, :, 0, :])/n_design
G_f = np.einsum('atnq,nm,btmq->ab', dfields, G_p, dfields)/n_design
def linearised_rates(G, sig, Ns):
out = {'fwd': [], 'pi2': [], 'W': [], 'dim': []}
for N in Ns:
A = N*G/sig**2; S = np.linalg.inv(np.eye(M) + A)
C_ = S + S @ A @ S + S @ np.outer(xi_true, xi_true) @ S
Ca = scale[:, None]*C_*scale[None, :] # in the coefficients a_k
out['fwd'].append(np.sqrt(np.trace(G @ C_)))
out['pi2'].append(np.sqrt(np.pi*np.trace(Ca[:2, :2]))); out['W'].append(np.sqrt(np.pi*np.trace(Ca)))
out['dim'].append(np.trace(np.eye(M) - S)) # sum of the shrinkages S_k
return {key: np.array(val) for key, val in out.items()}
N_line = np.logspace(np.log10(400), np.log10(8e4), 60)
lin = {'rho': linearised_rates(G_rho, sig_rho, N_line), 'f': linearised_rates(G_f, sig_f, N_line)}
lin_grid = {'rho': linearised_rates(G_rho, sig_rho, N_grid), 'f': linearised_rates(G_f, sig_f, N_grid)}
# fitted exponents, with the jackknife standard error over the R sequences (which includes the Monte Carlo error) and
# the Monte Carlo part alone (parametric bootstrap of the posterior means within their Monte Carlo standard errors)
Ns = np.array(N_grid)
def slope(y, Ns=Ns): return -np.polyfit(np.log(Ns), np.log(y), 1)[0]
def exponent(model, key):
loo = np.array([slope(average(model, key, [r2 for r2 in range(R) if r2 != r])) for r in range(R)])
se_jack = np.sqrt((R - 1)/R*np.sum((loo - loo.mean())**2))
m = np.array([[runs[model][r][N][key] for r in range(R)] for N in N_grid])
s = np.array([[runs[model][r][N]['mcse'][key] for r in range(R)] for N in N_grid])
g = np.random.default_rng(0)
boot = [slope(np.sqrt(np.clip(m + s*g.standard_normal(m.shape), 1e-300, None).mean(1))) for _ in range(2000)]
return slope(average(model, key)), se_jack, np.std(boot)
key_map = {'fwd': 'fwd2', 'pi2': 'pi2_2', 'W': 'W2'}
for model, name, sig in (('rho', '(M1)', sig_rho), ('f', '(M2)', sig_f)):
fw, p2, Wr = rates[model]['fwd2'], rates[model]['pi2_2'], rates[model]['W2']
(e1, j1, m1), (e2, j2, m2) = exponent(model, 'fwd2'), exponent(model, 'pi2_2')
print(f"{name}: fitted exponents over N = {N_grid[0]}-{N_grid[-1]}: forward {e1:.3f} +- {j1:.3f} (Monte Carlo {m1:.3f}; "
f"linearised {slope(lin_grid[model]['fwd']):.3f}), pi_2 W {e2:.3f} +- {j2:.3f} (Monte Carlo {m2:.3f}; "
f"linearised {slope(lin_grid[model]['pi2']):.3f})")
print(" chain / linearised, forward: " + " ".join(f"{a/b:.2f}" for a, b in zip(fw, lin_grid[model]['fwd'])))
print(" chain / linearised, pi_2 W : " + " ".join(f"{a/b:.2f}" for a, b in zip(p2, lin_grid[model]['pi2'])))
print(" sum of shrinkages d_N : " + " ".join(f"{v:.2f}" for v in lin_grid[model]['dim']))
print(f" r_N(W): chain {Wr[0]:.3f} -> {Wr[-1]:.3f}, linearised {lin_grid[model]['W'][0]:.3f} -> "
f"{lin_grid[model]['W'][-1]:.3f}")
print("theorem's exponent (alpha+1+kappa)/(2(alpha+1)+2 kappa+1) at alpha = 1/2:",
", ".join(f"kappa={kap}: {(1.5+kap)/(4+2*kap):.3f}" for kap in (1, 2, 5, 10, 50)))
fig, ax = paper_figure(0.95, 2.4, ncols=2)
for model, col, mk, name, sig in (('rho', 'C3', 'o', '(M1)', sig_rho), ('f', 'C0', 's', '(M2)', sig_f)):
lo, hi = spread(model, 'fwd2'); y = rates[model]['fwd2']
ax[0].loglog(N_line, lin[model]['fwd']/sig, '-', color=col, lw=1.1)
ax[0].errorbar(Ns, y/sig, yerr=[(y - lo)/sig, (hi - y)/sig], fmt=mk, color=col, ms=3.5,
elinewidth=0.7, capsize=1.5, label=f"model {name}")
for key, line, filled in (('pi2', '-', True), ('W', '--', False)):
lo, hi = spread(model, key_map[key]); y = rates[model][key_map[key]]
ax[1].loglog(N_line, lin[model][key], line, color=col, lw=1.1)
ax[1].errorbar(Ns, y, yerr=[y - lo, hi - y], fmt=mk, color=col, ms=3.5, mfc=None if filled else 'none',
elinewidth=0.7, capsize=1.5,
label=(rf"$\pi_2W$, {name}" if key == 'pi2' else rf"$W$, {name}"))
ref = np.array([N_line[0], N_line[-1]])
c0 = 0.55*lin['f']['fwd'][0]/sig_f*np.sqrt(N_line[0])
ax[0].loglog(ref, c0*ref**-0.5, 'k:', lw=1, label=r"$N^{-1/2}$")
c1 = 0.55*lin['rho']['pi2'][0]*np.sqrt(N_line[0])
ax[1].loglog(ref, c1*ref**-0.5, 'k:', lw=1, label=r"$N^{-1/2}$")
ax[0].set_xlabel("$N$"); ax[0].set_ylabel(r"$r_N(\mathscr{G})/\sigma_ϵ$")
ax[1].set_xlabel("$N$"); ax[1].set_ylabel(r"$r_N(\pi_2W)$, $r_N(W)$")
ax[0].legend(loc='lower left')
ax[1].legend(loc='lower left', fontsize=7, ncol=2, columnspacing=0.8, handlelength=1.5)
save_figure(fig, "contraction")
(M1): fitted exponents over N = 500-64000: forward 0.457 +- 0.022 (Monte Carlo 0.001; linearised 0.461), pi_2 W 0.508 +- 0.018 (Monte Carlo 0.002; linearised 0.495)
chain / linearised, forward: 0.95 0.94 0.92 0.92 0.97 0.95 0.98 0.94
chain / linearised, pi_2 W : 0.87 0.96 0.81 0.93 0.95 0.96 0.87 0.78
sum of shrinkages d_N : 2.03 2.14 2.27 2.44 2.61 2.77 2.89 2.98
r_N(W): chain 0.669 -> 0.339, linearised 0.653 -> 0.327
(M2): fitted exponents over N = 500-64000: forward 0.451 +- 0.022 (Monte Carlo 0.001; linearised 0.458), pi_2 W 0.468 +- 0.034 (Monte Carlo 0.002; linearised 0.494)
chain / linearised, forward: 0.94 0.99 0.94 1.10 1.00 0.96 1.00 1.00
chain / linearised, pi_2 W : 0.89 1.03 0.99 1.20 1.06 1.06 1.12 1.02
sum of shrinkages d_N : 1.91 2.01 2.10 2.22 2.38 2.55 2.72 2.85
r_N(W): chain 0.702 -> 0.362, linearised 0.716 -> 0.362
theorem's exponent (alpha+1+kappa)/(2(alpha+1)+2 kappa+1) at alpha = 1/2: kappa=1: 0.417, kappa=2: 0.438, kappa=5: 0.464, kappa=10: 0.479, kappa=50: 0.495