Validate stochastic Allen–Cahn¶
This notebook measures deterministic, spectral and stochastic numerical properties on a periodic unit domain. §1–5 and §10–14 contain verification experiments. The finite-step rates in the original §11 setup and the nonlinear radial spectrum in §8 are diagnostics. Sections 6–9 also include visual examples. The optional volume renderer is off by default.
Run from a fresh kernel with the project's test extra installed. The default
preset supports an installed package outside a checkout. Set
EXPONAX_VALIDATION_STRICT=1 in a clean checkout to collect release evidence.
The setup selects CPU and float64 before importing JAX. The four figures
and the text summary are written to validation/_output, or to the
directory named by EXPONAX_VALIDATION_OUTPUT.
The Allen–Cahn drift is νΔu + λ(u − u³). The phase-field setting follows
Allen & Cahn (1979). The physical noise amplitude σ
scales a Gaussian Q-Wiener field with modal weights
qₖ = (1 + |k|²)⁻ᵅ. All computations use the corrected noise normalisation.
For additive noise, sample_increment supplies the stochastic convolution
including σ, coarsened using the linear propagation over the next substep.
For multiplicative noise, it supplies a σ-free Wiener increment. The
pointwise kick is then propagated on the grid. Milstein adds the commutative
correction and requires α > d/2. The constructor’s continuum-regularity
warnings describe when a resolved finite-grid model lacks a classical
continuum interpretation. The 2-D white-noise limit requires care with
renormalisation Hairer, Ryser & Weber (2012).
See the noise model and
Lord, Powell & Shardlow (2014)
for the SPDE background.
The smoke preset (set EXPONAX_SPDE_PRESET=smoke) exercises every cell with small ensembles. Its outputs are diagnostic and it writes no artifacts.
Backend cpu, JAX 0.12.1, exponax 0.2.1 exponax-spde 0.5.0.dev0, x64 True
1 · Deterministic limit¶
Compare one and 50 steps using physical and Fourier entry points with the installed ETDRK1 base. Set σ=0, disable taming and match the λ, ν and dealiasing choices.
d, n, h = 1, 128, 0.001
u0 = (0.45 + 0.15 * jnp.sin(2 * jnp.pi * jnp.arange(n) / n))[None, :]
stoch = model(d, n, h, nu=0.01, sigma=0, dealiasing_fraction=0.5)
reference = ex.stepper.reaction.AllenCahn(
d,
1.0,
n,
h,
diffusivity=0.01,
first_order_coefficient=1,
third_order_coefficient=-1,
order=1,
dealiasing_fraction=0.5,
)
draw = jax.random.key(42)
def paired_parity(initial, a, b, steps):
def run(step):
def advance(field, _):
field = step(field)
return field, field
return np.asarray(
jax.jit(lambda u: jax.lax.scan(advance, u, None, length=steps)[1])(initial)
)
actual, exact = run(a), run(b)
exact_match = actual.tobytes() == exact.tobytes()
print(
f"Maximum errors after one and {steps} steps: "
f"{abs(actual[0] - exact[0]).max():.3g}, "
f"{abs(actual[-1] - exact[-1]).max():.3g}; bit-exact {exact_match}"
)
return exact_match
physical = paired_parity(u0, lambda u: stoch(u, key=draw), reference, 50)
fourier = paired_parity(
ex.fft(u0), lambda u: stoch.step_fourier(u, key=draw), reference.step_fourier, 50
)
record(
"§1 deterministic parity",
"PASS" if physical and fourier else "FAIL",
f"bit-exact physical={physical}, Fourier={fourier}, 1–50 steps",
)
jax.clear_caches()
_ = gc.collect()
Maximum errors after one and 50 steps: 0, 0; bit-exact True
Maximum errors after one and 50 steps: 0, 0; bit-exact True PASS §1 deterministic parity — bit-exact physical=True, Fourier=True, 1–50 steps
2 · Stationary spectrum in 1-D¶
At λ=0 the Fourier modes solve independent Ornstein–Uhlenbeck equations up to real-field conjugacy. In exponax's coefficient-extraction convention, the stationary power of a nonzero mode is (4^m\sigma^2 q_k/(2\nu|k|^2\ell^d)), where m counts the interior axes. DC has variance σ²t/ℓᵈ. For h=0.001 and 0.002, discard two time units and average for three more. The path counts and group sizes were frozen from dedicated pilots for the 10% spectral resolution, with a 20% margin on the t interval half-width. The across-group SE allows temporal dependence within paths; the first nonzero mode has a relative transient below 1.4×10⁻⁷ after burn-in.
nu, sigma, alpha = 0.1, 0.5, 1.5
fig, ax = plt.subplots()
target = stationary(1, 128, nu, sigma, alpha)
for h in (0.001, 0.002):
label = f"§2 h={h:g}"
group = spectra(
1, 128, h, int(5 / h), int(2 / h), nu, sigma, alpha, *SPECTRAL_PLAN[label]
)
compare_spectrum(label, group, target, [(1,), (2,), (3,)])
ax.loglog(np.arange(1, 65), group.mean(axis=0)[1:], ".", label=f"h={h:g}")
ax.loglog(np.arange(1, 65), target[1:], "k-", label="OU stationary")
ax.set(xlabel="Mode", ylabel="Coefficient power")
ax.legend()
figure(fig)
jax.clear_caches()
_ = gc.collect()
§2 h=0.001 mode (1,): mean 0.00049003552, SE 9.95e-06, truth 0.00049178466, resolution 4.92e-05, ratio 0.9964 §2 h=0.001 mode (2,): mean 1.5811236e-05, SE 1.91e-07, truth 1.5805505e-05, resolution 1.58e-06, ratio 1.0004 §2 h=0.001 mode (3,): mean 2.1040801e-06, SE 1.54e-08, truth 2.092346e-06, resolution 2.09e-07, ratio 1.0056
§2 h=0.002 mode (1,): mean 0.000489992, SE 1.12e-05, truth 0.00049178466, resolution 4.92e-05, ratio 0.9964 §2 h=0.002 mode (2,): mean 1.580067e-05, SE 1.75e-07, truth 1.5805505e-05, resolution 1.58e-06, ratio 0.9997 §2 h=0.002 mode (3,): mean 2.1056019e-06, SE 1.41e-08, truth 2.092346e-06, resolution 2.09e-07, ratio 1.0063
3 · Stationary spectrum in 2-D¶
Use N=32 and h=0.001 with the frozen pilot-sized independent groups. The coefficient-extraction factor is four on the lowest axial modes and sixteen on the lowest interior modes. Exclude DC, and compare both types. The additive stochastic increment spans the resolved grid. Dealiasing pertains to the nonlinear drift.
nu, sigma, alpha = 0.1, 0.5, 1.5
label = "§3 axes and interior"
group = spectra(2, 32, 0.001, 3000, 1000, nu, sigma, alpha, *SPECTRAL_PLAN[label])
target = stationary(2, 32, nu, sigma, alpha)
compare_spectrum(
"§3 axes and interior", group, target, [(1, 0), (0, 1), (1, 1), (2, 2)]
)
fig, ax = plt.subplots()
k2, _, _ = geometry(2, 32)
mask = k2 > 0
ax.loglog(np.sqrt(k2[mask]), group.mean(axis=0)[mask], ".", label="Measured")
ax.loglog(np.sqrt(k2[mask]), target[mask], "+", label="OU stationary")
ax.set(xlabel="Wavenumber magnitude", ylabel="Coefficient power")
ax.legend()
figure(fig)
jax.clear_caches()
_ = gc.collect()
§3 axes and interior mode (1, 0): mean 0.00051031222, SE 9.94e-06, truth 0.00049178466, resolution 4.92e-05, ratio 1.0377 §3 axes and interior mode (0, 1): mean 0.00047954704, SE 9.37e-06, truth 0.00049178466, resolution 4.92e-05, ratio 0.9751 §3 axes and interior mode (1, 1): mean 0.0003555996, SE 5.24e-06, truth 0.00035428835, resolution 3.54e-05, ratio 1.0037 §3 axes and interior mode (2, 2): mean 1.1325317e-05, SE 8.39e-08, truth 1.1229135e-05, resolution 1.12e-06, ratio 1.0086
4 · Noise colour¶
From zero initial data multiply the stationary spectrum by \(1-\exp(-2\nu|k|^2t)\) at t=1.5. Compare α=0, 1, 2, 3 with fixed σ=0.3. The continuum tail scales as |k|⁻²ᵅ⁻². Fit log-power slopes over the predeclared modes 12–24 in independent groups. Their SEs describe slope uncertainty. The §14 spectrum checks use the finite-time mode means and a 10% resolution.
n, nu, sigma, end, h = 128, 0.05, 0.3, 1.5, 0.0005
k2, _, _ = geometry(1, n)
modes = np.arange(1, n // 2 + 1)
band = np.arange(12, 25)
fig, ax = plt.subplots()
for alpha in range(4):
target = stationary(1, n, nu, sigma, alpha) * (-np.expm1(-2 * nu * k2 * end))
label = f"§4 alpha={alpha}"
group = spectra(1, n, h, 3000, 2999, nu, sigma, alpha, *SPECTRAL_PLAN[label])
compare_spectrum(f"§4 alpha={alpha}", group, target, [(1,), (4,), (16,)])
fits = np.polyfit(np.log(band), np.log(group[:, band]).T, 1)[0]
fit_se = fits.std(ddof=1) / np.sqrt(fits.size)
expected = np.polyfit(np.log(band), np.log(target[band]), 1)[0]
print(
f"Modes 12–24: group-log slope {fits.mean():.4f} ± {fit_se:.3g} SE, "
f"finite-grid target {expected:.4f}, tail {-2 * alpha - 2}"
)
(line,) = ax.loglog(modes, group.mean(axis=0)[1:], ".", label=f"α={alpha}")
ax.loglog(modes, target[1:], "-", color=line.get_color(), alpha=0.6)
ax.set(xlabel="Mode", ylabel="Terminal coefficient power")
ax.legend()
figure(fig)
jax.clear_caches()
_ = gc.collect()
§4 alpha=0 mode (1,): mean 0.090785595, SE 0.00168, truth 0.090944636, resolution 0.00909, ratio 0.9983 §4 alpha=0 mode (4,): mean 0.0057342324, SE 9.75e-05, truth 0.0056993166, resolution 0.00057, ratio 1.0061 §4 alpha=0 mode (16,): mean 0.00036372006, SE 6.4e-06, truth 0.00035620729, resolution 3.56e-05, ratio 1.0211 Modes 12–24: group-log slope -2.0234 ± 0.0228 SE, finite-grid target -2.0000, tail -2
§4 alpha=1 mode (1,): mean 0.0022328348, SE 4.52e-05, truth 0.0022467438, resolution 0.000225, ratio 0.9938 §4 alpha=1 mode (4,): mean 9.170918e-06, SE 2.13e-07, truth 9.0085741e-06, resolution 9.01e-07, ratio 1.0180 §4 alpha=1 mode (16,): mean 3.5377124e-08, SE 7.67e-10, truth 3.5241966e-08, resolution 3.52e-09, ratio 1.0038 Modes 12–24: group-log slope -4.0158 ± 0.0297 SE, finite-grid target -3.9998, tail -4
§4 alpha=2 mode (1,): mean 5.53336e-05, SE 1.12e-06, truth 5.5504735e-05, resolution 5.55e-06, ratio 0.9969 §4 alpha=2 mode (4,): mean 1.4217817e-08, SE 3.07e-10, truth 1.4239323e-08, resolution 1.42e-09, ratio 0.9985 §4 alpha=2 mode (16,): mean 3.4938432e-12, SE 7.12e-14, truth 3.4867231e-12, resolution 3.49e-13, ratio 1.0020 Modes 12–24: group-log slope -5.9839 ± 0.0252 SE, finite-grid target -5.9996, tail -6
§4 alpha=3 mode (1,): mean 1.3595332e-06, SE 2.29e-08, truth 1.371218e-06, resolution 1.37e-07, ratio 0.9915 §4 alpha=3 mode (4,): mean 2.2681396e-11, SE 4.97e-13, truth 2.2507259e-11, resolution 2.25e-12, ratio 1.0077 §4 alpha=3 mode (16,): mean 3.4830525e-16, SE 7.14e-18, truth 3.449648e-16, resolution 3.45e-17, ratio 1.0097 Modes 12–24: group-log slope -8.0492 ± 0.0266 SE, finite-grid target -7.9995, tail -8
5 · Conditional kick laws¶
For a fixed state u, the additive kick has zero mean and its covariance follows the OU convolution. Let C be the plain coloured grid covariance and D=diag(u). For multiplicative Euler–Maruyama the conditional covariance is σ² Eₕ D C D Eₕᵀ, where Eₕ is the linear propagator. Compare kick mean and variance, using empirical SEs derived from centred first and second moments. The nonlinear rollout statistics at the end of the section describe a separate finite-time diagnostic.
n, h, nu, sigma, alpha = 64, 0.0005, 0.01, 0.15, 1.5
u0 = 0.3 + 0.05 * ex.ic.GaussianRandomField(1, powerlaw_exponent=3.0, zero_mean=True)(
n, key=jax.random.key(99)
)
settings = dict(nu=nu, alpha=alpha, use_taming=True)
deter = model(1, n, h, sigma=0, **settings)
baseline = deter(u0, key=jax.random.key(8))
lam = 1 - nu * (2 * np.pi * np.fft.rfftfreq(n) * n) ** 2
q = (1 + (1 - lam) / nu) ** (-alpha)
eye = np.eye(n)
prop = np.fft.irfft(np.exp(h * lam) * np.fft.rfft(eye), n=n)
cov = n * h * np.fft.irfft(q * np.fft.rfft(eye), n=n)
weights = np.ones(n // 2 + 1)
weights[1:-1] = 2
locations = [0, 16, 32, 48]
paths = 128 if SMOKE else 8192
variance_ok = True
worst = 0.0
fig, axes = plt.subplots(1, 2, figsize=(10, 3))
for index, noise in enumerate(("additive", "multiplicative")):
step = model(1, n, h, sigma=sigma, noise_type=noise, **settings)
keys = jax.random.split(jax.random.key(215 + index), paths)
def observe(key, step=step):
return (step(u0, key=key) - baseline)[0, jnp.asarray(locations)]
draws = np.asarray(jax.jit(lambda k: jax.lax.map(observe, k, batch_size=128))(keys))
if noise == "additive":
expected = np.full(n, sigma**2 * np.dot(weights, q * ou_factor(lam, h)))
else:
scaled = prop * np.asarray(u0)
expected = sigma**2 * np.diag(scaled @ cov @ scaled.T)
target = expected[locations]
measured = draws.var(axis=0, ddof=1)
se_mean = np.sqrt(measured / paths)
se_var = (draws - draws.mean(axis=0)) ** 2
se_var = se_var.std(axis=0, ddof=1) / np.sqrt(paths)
z = max(
np.max(abs(draws.mean(axis=0)) / se_mean),
np.max(abs(measured - target) / se_var),
)
worst = max(worst, z)
variance_ok &= z <= 5
print(
f"{noise}: variance={measured}, reference={target}, "
f"empirical SE={se_var}, max z={z:.3f}"
)
kernel = jax.jit(
spde.stochastic_ensemble_rollout(step, 500, 16, stride=10, include_init=True)
)
sum_u, sum_u2 = 0, 0
groups = 1 if SMOKE else 16
for key in jax.random.split(jax.random.key(10 + index), groups):
chunk = np.asarray(kernel(u0, key))[:, :, 0]
sum_u = sum_u + chunk.sum(axis=0)
sum_u2 = sum_u2 + (chunk**2).sum(axis=0)
mean = sum_u / (groups * 16)
var = sum_u2 / (groups * 16) - mean**2
axes[0].plot(mean[-1], label=noise)
axes[1].plot(var[-1], label=noise)
for ax, label in zip(axes, ("Final mean", "Final variance"), strict=True):
ax.set(xlabel="Grid site", ylabel=label)
ax.legend()
figure(fig)
record(
"§5 conditional kick moments",
"PASS" if variance_ok else "FAIL",
f"worst {worst:.3f} SE, five-SE two-sided band",
)
jax.clear_caches()
_ = gc.collect()
additive: variance=[1.13586299e-05 1.13164529e-05 1.13070202e-05 1.13137665e-05], reference=[1.13611335e-05 1.13611335e-05 1.13611335e-05 1.13611335e-05], empirical SE=[1.77064101e-07 1.75630020e-07 1.75474188e-07 1.76555614e-07], max z=0.308
multiplicative: variance=[1.02181367e-06 1.01686513e-06 1.02233518e-06 1.02193747e-06], reference=[1.02549093e-06 1.02004732e-06 1.02311387e-06 1.02514762e-06], empirical SE=[1.56823929e-08 1.57159050e-08 1.57510183e-08 1.57828667e-08], max z=0.234
PASS §5 conditional kick moments — worst 0.308 SE, five-SE two-sided band
6 · Initial conditions¶
Use a Gaussian random field, white initial data and a nonzero constant field. The visual scale uses the one-step variance match σ=0.0252394 in place of 0.1. Grid N=256, h=0.0005, ν=0.008, λ=1, α=1.5.
step = model(1, 256, 0.0005, nu=0.008, sigma=0.0252394, use_taming=True)
initials = (
grf(1, 256, 0, power=3.5),
ex.ic.WhiteNoise(1)(256, key=jax.random.key(1)),
0.5 * jnp.ones((1, 256)),
)
fig, axes = plt.subplots(1, 3, figsize=(11, 3), sharey=True)
for i, (initial, ax) in enumerate(zip(initials, axes, strict=True)):
states = rollout(step, initial, 2000, i + 2, stride=200)
ax.plot(states[0], alpha=0.4, label="t=0")
ax.plot(states[5], "--", label="t=0.5")
ax.plot(states[-1], label="t=1")
ax.set_title(("GRF", "White", "Constant")[i])
ax.legend()
figure(fig)
jax.clear_caches()
_ = gc.collect()
7 · 1-D README figures¶
The maintainer’s illustration uses the classical one-dimensional space-time white-noise setting, in which walls wander and merge (Funaki, 1995).
n, h, stride = 256, 0.001, 25
x = jnp.arange(n) / n
u0 = 0.10 + 0.9 * grf(1, n, 10, power=0.5, zero_mean=True)
step = model(1, n, h, nu=0.0005, reaction=1.0, sigma=0.05, alpha=0.0)
states = rollout(step, u0, 300 if SMOKE else 7500, 11, stride=stride)
smooth = gaussian_filter1d(states, 3, axis=-1, mode="wrap")
positive = smooth > 0
edges = (positive != np.roll(positive, 1, axis=-1)).sum(axis=-1)
a_max = float(np.max(abs(states)))
a_edges = edges[[0, 3, 6, 9, 12] if SMOKE else [0, 30, 60, 120, 180, 240, 300]].tolist()
a_positive = positive[[0, 4, 8, 12] if SMOKE else [0, 60, 150, 300]].mean(axis=-1)
a_tail = float((abs(states) > 1.2).mean())
a_hash = sha256(np.ascontiguousarray(states).tobytes()).hexdigest()[:16]
print(
f"A: max |u|={a_max:.9g}, smoothed sign changes={a_edges}, "
f"smoothed positive fractions={a_positive.tolist()}, tail={a_tail:.9g}, "
f"SHA-256 prefix={a_hash}, states={states.shape}"
)
if not SMOKE:
assert len(states) == 301
assert np.round(a_max, 3) == 1.525, "A peak differs from the approved prototype."
assert a_edges == [12, 8, 8, 4, 4, 4, 4], "A interface counts differ."
assert np.round(a_positive, 2).tolist() == [0.74, 0.72, 0.62, 0.59], (
"A phase fractions differ."
)
assert np.round(a_tail, 4) == 0.0129, "A tail fraction differs."
fig, ax = plt.subplots(figsize=(6.2, 4))
image = ax.imshow(
states,
aspect="auto",
origin="lower",
cmap="RdBu_r",
vmin=-1.25,
vmax=1.25,
extent=(0, 1, 0, (len(states) - 1) * h * stride),
)
ax.set(xlabel="Space", ylabel="Time")
fig.colorbar(image, ax=ax, label="Value")
figure(fig, "stochastic_allen_cahn_1d_spacetime.png")
fig, ax = plt.subplots(figsize=(6.4, 4.8), dpi=100)
canvas = FigureCanvasAgg(fig)
(line,) = ax.plot(np.asarray(x), states[0])
ax.set(xlabel="Space", ylabel="Value", xlim=(-0.05, 1.05), ylim=(-1.5, 1.5))
ax.grid(True)
timer = ax.set_title("")
if not SMOKE:
frames = []
for index, state in enumerate(states):
line.set_ydata(state)
timer.set_text(f"t = {index * h * stride:.2f}")
canvas.draw()
frame = Image.fromarray(np.array(canvas.buffer_rgba()))
frames.append(frame.convert("P", palette=Image.Palette.ADAPTIVE, colors=32))
frames[0].save(
OUTPUT / "stochastic_allen_cahn_1d_evolution.gif",
save_all=True,
append_images=frames[1:],
duration=50,
loop=0,
optimize=True,
)
plt.close(fig)
gif_size = (OUTPUT / "stochastic_allen_cahn_1d_evolution.gif").stat().st_size
print("Encoded GIF bytes:", gif_size)
del frames, states
jax.clear_caches()
_ = gc.collect()
A: max |u|=1.52450173, smoothed sign changes=[12, 8, 8, 4, 4, 4, 4], smoothed positive fractions=[0.73828125, 0.71875, 0.6171875, 0.58984375], tail=0.0128997093, SHA-256 prefix=6938da45cc7ccb74, states=(301, 256)
Encoded GIF bytes: 3003901
8 · 2-D README figures¶
In the maintainer’s illustration, interfaces move by curvature (Allen & Cahn, 1979), so the minority phase shrinks (Bray, 1994).
n, h, stride = (32, 0.001, 10) if SMOKE else (256, 0.001, 100)
u0 = 0.15 + 0.8 * grf(2, n, 20, power=2.5, zero_mean=True)
step = model(2, n, h, nu=0.0008, reaction=10, sigma=0.12, alpha=0.5, use_taming=True)
states = rollout(step, u0, (100 if SMOKE else 10000), 21, stride=stride)
v_positive = (
states[[0, 2, 4, 6, 8, 10] if SMOKE else [0, 5, 10, 25, 50, 100]] > 0
).mean(axis=(-2, -1))
v_hash = sha256(np.ascontiguousarray(states).tobytes()).hexdigest()[:16]
print(
f"V: positive fractions={v_positive.tolist()}, SHA-256 prefix={v_hash}, "
f"states={states.shape}"
)
if not SMOKE:
assert len(states) == 101
assert np.round(v_positive, 3).tolist() == [
0.751,
0.749,
0.757,
0.790,
0.815,
0.847,
], "V phase fractions differ from the approved prototype."
fig, axes = plt.subplots(1, 4, figsize=(11, 3.35), layout="constrained")
for index, ax in zip((0, 2, 5, 10) if SMOKE else (0, 5, 25, 100), axes, strict=True):
image = ax.imshow(
states[index], origin="lower", cmap="RdBu_r", vmin=-1.25, vmax=1.25
)
ax.set_title(f"t={index * h * stride:.4g}")
ax.set_axis_off()
fig.colorbar(image, ax=axes, shrink=0.64, label="u")
figure(fig, "stochastic_allen_cahn_2d_evolution.png")
palette = np.uint8(255 * plt.get_cmap("RdBu_r")(np.linspace(0, 1, 48))[:, :3]).ravel()
if not SMOKE:
frames = []
for state in states:
indices = np.uint8(np.rint(47 * np.clip((state[::-1] + 1.25) / 2.5, 0, 1)))
frame = Image.fromarray(indices)
frame.putpalette(palette.tolist())
frames.append(frame)
frames[0].save(
OUTPUT / "stochastic_allen_cahn_2d_animation.gif",
save_all=True,
append_images=frames[1:],
duration=80,
loop=0,
optimize=True,
)
gif_size = (OUTPUT / "stochastic_allen_cahn_2d_animation.gif").stat().st_size
print("Encoded GIF bytes:", gif_size)
del frames, states
jax.clear_caches()
_ = gc.collect()
V: positive fractions=[0.7507781982421875, 0.748870849609375, 0.7565765380859375, 0.78955078125, 0.8150482177734375, 0.84716796875], SHA-256 prefix=01a89051f5ae506d, states=(101, 256, 256)
Encoded GIF bytes: 3512998
8b · Radial PSD¶
Keep σ=0.3 in the quantitative comparison. Normalise the raw FFT by the number of grid sites. Double the power at interior last-axis indices when taking the full-spectrum sum. Divide shell power by the full-spectrum shell count for radial means. Compare the linear λ=0 control with its finite-time OU spectrum. The exact Parseval identity checks the sum; the nonlinear peak is descriptive.
n, h, nu, sigma, alpha = 256, 0.0005, 0.01, 0.3, 2
if SMOKE:
n = 32
initial = grf(2, n, 20)
nonlinear = rollout(
model(2, n, h, nu=nu, reaction=5, sigma=sigma, alpha=alpha, use_taming=True),
initial,
16 if SMOKE else 1500,
21,
stride=4 if SMOKE else 375,
)
linear = rollout(
model(2, n, h, nu=nu, reaction=0, sigma=sigma, alpha=alpha),
jnp.zeros_like(initial),
16 if SMOKE else 1500,
21,
stride=4 if SMOKE else 375,
)
k2, _, weight = geometry(2, n)
shell = np.rint(np.sqrt(k2) / (2 * np.pi)).astype(int)
count = np.bincount(shell.ravel(), weights=weight.ravel())
def radial(power):
total = np.bincount(shell.ravel(), weights=(weight * power).ravel())
return np.divide(total, count, out=np.zeros_like(total), where=count > 0)
fig, ax = plt.subplots()
residual = 0.0
for i, u in enumerate(nonlinear):
power = abs(np.fft.rfft2(u) / n**2) ** 2
residual = max(residual, abs(np.sum(weight * power) - np.mean(u**2)))
ax.loglog(radial(power)[1:80], label=f"AC t={i * (4 if SMOKE else 375) * h:g}")
power = abs(np.fft.rfft2(linear[-1]) / n**2) ** 2
target = (
sigma**2 * (1 + k2) ** (-alpha) * ou_factor(-nu * k2, (16 if SMOKE else 1500) * h)
)
ax.loglog(radial(power)[1:80], ".", label="Linear sample")
ax.loglog(radial(target)[1:80], "k--", label="Linear OU mean")
ax.set(xlabel="Shell index", ylabel="Raw mean mode power")
ax.legend()
figure(fig)
record(
"§8 radial PSD normalisation",
"PASS" if residual <= 1e-12 else "FAIL",
f"max Parseval residual {residual:.3g}",
)
jax.clear_caches()
_ = gc.collect()
PASS §8 radial PSD normalisation — max Parseval residual 2.22e-16
9 · 3-D midplanes¶
Inspect static final midplanes at N=32,
h=0.0005, λ=5, ν=0.0005, σ=1.14311 and α=2. Set
RENDER_VOLUME = True in setup to opt into volume rendering with the
vape4d extra.
n, h, stride = (12, 0.0005, 2) if SMOKE else (32, 0.0005, 10)
step = model(3, n, h, nu=0.0005, reaction=5, sigma=1.14311, alpha=2, use_taming=True)
volume = rollout(
step, grf(3, n, 30, power=1.5), (8 if SMOKE else 500), 31, stride=stride
)
mid = n // 2
fig, axes = plt.subplots(1, 3, figsize=(9, 3))
for ax, slc, label in zip(
axes,
(volume[-1, mid], volume[-1, :, mid], volume[-1, :, :, mid]),
("yz", "xz", "xy"),
strict=True,
):
ax.imshow(slc, cmap="RdBu_r", origin="lower", vmin=-1.25, vmax=1.25)
ax.set_title(f"{label} midplane")
ax.set_axis_off()
figure(fig)
if RENDER_VOLUME:
from IPython.display import HTML
animation = ex.viz.animate_state_3d(
volume[::5, None],
vlim=(-1.25, 1.25),
dt=h * stride * 5,
include_init=True,
cmap="RdBu_r",
bg_color="white",
resolution=256,
)
display(HTML(animation.to_jshtml()))
del volume
jax.clear_caches()
_ = gc.collect()
10 · Additive strong order¶
Each adjacent approximation uses
the same Brownian path through coarsen_increments. For exponential
schemes and stochastic order, see
Jentzen & Kloeden (2009). Accumulate fine
increments inside each macro-block and keep terminal squared errors.
Use the exact λ=0 semigroup composition as a control. For the nonlinear
fixed-grid comparison, check the paired-bootstrap 95% interval against
[0.75, 1.25] for the leading O(h) RMS error. A two-sided physverify
check is secondary. Separately report the uncertainty of the RMS estimates.
def paired_levels(
initial, levels, horizon, factory, paths, batch, seed, *, exact_gbm=None
):
"""Carry only states and one fine block of increments per path."""
if SMOKE:
paths = batch
levels = tuple(levels)
ratios = tuple(levels[-1] // k for k in levels)
block_steps = ratios[0]
methods = tuple(tuple(make(k) for k in levels) for make in factory)
fine = methods[0][-1]
n = initial.shape[-1]
start = ex.fft(
jnp.broadcast_to(initial, (batch, *initial.shape)), num_spatial_dims=1
)
def advance(solver, field, inc):
step = jax.vmap(solver.step_with_increment)
return jax.lax.scan(lambda u, dw: (step(u, dw), None), field, inc)[0]
@jax.jit
def sample(key):
def block(carry, i):
states, brownian = carry
keys = jax.random.split(jax.random.fold_in(key, i), (block_steps, batch))
draws = jax.vmap(jax.vmap(fine.sample_increment))(keys)
increments = tuple(
jax.vmap(jax.vmap(fine.coarsen_increments, in_axes=1))(
draws.reshape(-1, ratio, *draws.shape[1:])
)
if ratio > 1
else draws
for ratio in ratios
)
next_states = tuple(
tuple(
advance(solver, field, inc)
for solver, field, inc in zip(group, state, increments, strict=True)
)
for group, state in zip(methods, states, strict=True)
)
if exact_gbm is not None:
brownian = brownian + draws[:, :, 0, 0].real.sum(axis=0) / n
return (next_states, brownian), None
init = tuple((start,) * len(levels) for _ in methods), jnp.zeros(batch)
(terminal, brownian), _ = jax.lax.scan(block, init, jnp.arange(levels[0]))
values = jnp.asarray(terminal)
error = ex.ifft(
values[:, :-1] - values[:, 1:], num_spatial_dims=1, num_points=n
)
squared = jnp.mean(error**2, axis=(-2, -1))
if exact_gbm is None:
return squared
sigma = exact_gbm
exact = initial[0, 0] * jnp.exp(sigma * brownian - 0.5 * sigma**2 * horizon)
return squared, jnp.sqrt(
jnp.mean((values[:, -1, :, 0, 0].real / n - exact) ** 2, axis=-1)
)
root = jax.random.key(seed)
start_time = perf_counter()
first = jax.device_get(sample(jax.random.fold_in(root, 0)))
warm = perf_counter() - start_time
start_time = perf_counter()
blocks = [
jax.device_get(sample(jax.random.fold_in(root, i)))
for i in range(1, paths // batch)
]
remaining = perf_counter() - start_time
print(f"{paths} paths, batch {batch}: first {warm:.2f}s, rest {remaining:.2f}s")
if exact_gbm is None:
return np.concatenate([first, *blocks], axis=-1)
squares, terminal_rms = zip(first, *blocks, strict=True)
print(
f"Finest terminal RMS versus exact geometric Brownian motion: "
f"{np.sqrt(np.mean(np.array(terminal_rms) ** 2, axis=0))}"
)
return np.concatenate(squares, axis=-1)
def interval(hs, squared, seed):
x = np.log(hs)
x = x - x.mean()
weights = x / (x @ x)
rng = np.random.default_rng(seed)
m = squared.shape[-1]
bootstrap = []
for _ in range(32):
subset = rng.integers(0, m, (32, m))
bootstrap.append(0.5 * (weights @ np.log(squared[:, subset].mean(axis=-1))))
mse = squared.mean(axis=-1)
rse = squared.std(axis=-1, ddof=1) / (2 * np.sqrt(m) * mse)
return np.sqrt(mse), np.quantile(np.concatenate(bootstrap), (0.025, 0.975)), rse
def strong_order(label, hs, squared, expected, band, seed, secondary_tol=None):
rms, (lo, hi), rse = interval(hs, squared, seed)
lo_tol, hi_tol = (
(expected - band[0], band[1] - expected)
if secondary_tol is None
else (secondary_tol, secondary_tol)
)
verdict_order = check_order(
hs,
rms,
expected,
tol_low=lo_tol,
tol_high=hi_tol,
fit_points=len(hs),
)
if verdict_order.status == "FAIL" or hi < band[0] or lo > band[1]:
status = "FAIL"
elif (
verdict_order.status == "PASS"
and band[0] <= lo <= hi <= band[1]
and max(rse) <= 0.03
):
status = "PASS"
else:
status = "INCONCLUSIVE"
pairwise_slopes = np.log2(rms[:-1] / rms[1:])
print(f"{label}: RMS {rms}, RMS relative SE {rse}, pairwise {pairwise_slopes}")
record(
label,
status,
f"order {verdict_order.fitted:.4f}, paired 95% [{lo:.4f}, {hi:.4f}], "
f"band [{band[0]:g}, {band[1]:g}], physverify {verdict_order.status}",
)
return rms
n, end, levels = 128, 0.125, (64, 128, 256, 512, 1024)
ic = grf(1, n, 40)
base = dict(nu=0.05, sigma=0.1, alpha=1.5, use_taming=True)
fine = model(1, n, end / 1024, reaction=0, **base)
coarse = model(1, n, end / 512, reaction=0, **base)
initial = ex.fft(ic)
draws = jax.vmap(fine.sample_increment)(jax.random.split(jax.random.key(219), 2))
sequential = fine.step_with_increment(
fine.step_with_increment(initial, draws[0]), draws[1]
)
direct = coarse.step_with_increment(initial, fine.coarsen_increments(draws))
gap = float(jnp.max(jnp.abs(sequential - direct)))
record(
"§10 exact OU coupling",
"PASS" if gap <= 1e-12 else "FAIL",
f"max Fourier difference {gap:.3g}",
)
runs = (lambda count: model(1, n, end / count, reaction=0.5, **base),)
squares = paired_levels(ic, levels, end, runs, 1024, 32, 50)[0]
hs = end / np.array(levels[:-1])
errors = strong_order(
"§10 additive fixed-grid order", hs, squares, 1, (0.75, 1.25), 224
)
fig, ax = plt.subplots()
ax.loglog(hs, errors, ".-", label="Coupled adjacent RMS")
ax.loglog(hs, errors[0] * hs / hs[0], "k--", label="Order one")
ax.set(xlabel="h", ylabel="RMS")
ax.legend()
figure(fig)
jax.clear_caches()
_ = gc.collect()
PASS §10 exact OU coupling — max Fourier difference 9.93e-16
1024 paths, batch 32: first 1.15s, rest 2.82s §10 additive fixed-grid order: RMS [3.37754869e-05 1.70941097e-05 8.93788957e-06 4.35878781e-06], RMS relative SE [0.0222093 0.02207539 0.0207613 0.0215072 ], pairwise [0.98247729 0.93549316 1.03600725] PASS §10 additive fixed-grid order — order 0.9797, paired 95% [0.9577, 0.9996], band [0.75, 1.25], physverify PASS
11 · Multiplicative strong orders¶
Share σ-free increments between Euler–Maruyama and Milstein. Plot the original N=64 setup and the supplemental N=32 fixed-grid benchmark from #20 side by side. The slow asymptotic regime at finite step sizes can contain drift error; the original rates are descriptive. Predeclare paired bands [0.35, 0.70] and [0.80, 1.25] for the supplemental benchmark. Compare the nearly homogeneous control with exact geometric Brownian motion and paired bands [0.40, 0.65] and [0.85, 1.20]. The exact scalar solution is given by Kloeden & Platen (1992). The first non-DC noise amplitude at α=20 is below 10⁻¹⁶ of the DC amplitude.
def mult_factory(n, end, nu, reaction, sigma, alpha, *, taming=False):
def method(count, milstein):
return model(
1,
n,
end / count,
nu=nu,
reaction=reaction,
sigma=sigma,
alpha=alpha,
noise_type="multiplicative",
use_milstein=milstein,
use_taming=taming,
)
return tuple(
lambda count, milstein=milstein: method(count, milstein)
for milstein in (False, True)
)
labels = ("Euler–Maruyama", "Milstein")
n, end, levels = 64, 0.125, (256, 512, 1024, 2048)
ic = 0.3 + 0.05 * ex.ic.GaussianRandomField(1, powerlaw_exponent=3.0, zero_mean=True)(
n, key=jax.random.key(42)
)
hs = end / np.array(levels[:-1])
original = paired_levels(
ic,
levels,
end,
mult_factory(n, end, 0.05, 0.5, 0.1, 1.5, taming=True),
2048,
32,
42,
)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
for name, squared in zip(labels, original, strict=True):
rms, (lo, hi), rse = interval(hs, squared, 226)
fit = np.polyfit(np.log(hs), np.log(rms), 1)[0]
print(
f"Original N=64 {name}: RMS {rms}, RSE {rse}, descriptive slope {fit:.4f} "
f"95% [{lo:.4f}, {hi:.4f}]"
)
record(
f"§11 N=64 {name}",
"DIAGNOSTIC",
f"order {fit:.4f}, paired 95% [{lo:.4f}, {hi:.4f}]",
)
axes[0].loglog(hs, rms, ".-", label=name)
axes[0].set_title("Original N=64 configuration")
n, end, levels = 32, 0.25, (32, 64, 128, 256, 512, 1024)
ic = (0.5 + 0.2 * jnp.sin(2 * jnp.pi * jnp.arange(n) / n))[None]
hs = end / np.array(levels[:-1])
supplement = paired_levels(
ic, levels, end, mult_factory(n, end, 0.01, 1, 0.5, 2), 4096, 128, 262
)
for name, squared, order, band in zip(
labels,
supplement,
(0.5, 1),
((0.35, 0.70), (0.8, 1.25)),
strict=True,
):
rms = strong_order(
f"§11 #20 N=32 {name}", hs, squared, order, band, 263, secondary_tol=0.2
)
(line,) = axes[1].loglog(hs, rms, ".-", label=name)
axes[1].loglog(hs, rms[-1] * (hs / hs[-1]) ** order, "--", color=line.get_color())
axes[1].set_title("Supplemental N=32 benchmark")
for ax in axes:
ax.set(xlabel="h", ylabel="Coupled RMS")
ax.legend(fontsize=8)
figure(fig)
n, end, levels = 8, 1, (16, 32, 64, 128, 256)
hs = end / np.array(levels[:-1])
gbm_squared = paired_levels(
jnp.full((1, n), 0.8),
levels,
end,
mult_factory(n, end, 0.05, 0, 0.5, 20),
4096,
128,
604,
exact_gbm=0.5,
)
for name, squared, order, band in zip(
labels,
gbm_squared,
(0.5, 1),
((0.40, 0.65), (0.85, 1.20)),
strict=True,
):
strong_order(f"§11 geometric Brownian {name}", hs, squared, order, band, 227)
jax.clear_caches()
_ = gc.collect()
2048 paths, batch 32: first 1.99s, rest 13.75s Original N=64 Euler–Maruyama: RMS [1.25444981e-05 8.85969703e-06 6.34733584e-06], RSE [0.01529945 0.01482928 0.0150697 ], descriptive slope 0.4914 95% [0.4614, 0.5231] DIAGNOSTIC §11 N=64 Euler–Maruyama — order 0.4914, paired 95% [0.4614, 0.5231] Original N=64 Milstein: RMS [9.66832906e-07 4.91819808e-07 2.47303600e-07], RSE [0.00432582 0.00421387 0.00428662], descriptive slope 0.9835 95% [0.9789, 0.9884] DIAGNOSTIC §11 N=64 Milstein — order 0.9835, paired 95% [0.9789, 0.9884]
4096 paths, batch 128: first 1.41s, rest 6.46s §11 #20 N=32 Euler–Maruyama: RMS [0.00319866 0.00217966 0.00151851 0.00108118 0.00075696], RMS relative SE [0.01225573 0.01233768 0.01218838 0.01247897 0.01239912], pairwise [0.55336287 0.52144923 0.4900519 0.51431219] PASS §11 #20 N=32 Euler–Maruyama — order 0.5170, paired 95% [0.5071, 0.5277], band [0.35, 0.7], physverify PASS
§11 #20 N=32 Milstein: RMS [6.18539018e-04 3.01278944e-04 1.52010092e-04 7.61376433e-05 3.73688257e-05], RMS relative SE [0.02463992 0.02273084 0.02257207 0.02372933 0.02214427], pairwise [1.03776475 0.98693275 0.99748529 1.02677468] PASS §11 #20 N=32 Milstein — order 1.0082, paired 95% [0.9980, 1.0190], band [0.8, 1.25], physverify PASS
4096 paths, batch 128: first 0.92s, rest 0.49s Finest terminal RMS versus exact geometric Brownian motion: [0.01005571 0.00018205] §11 geometric Brownian Euler–Maruyama: RMS [0.02898131 0.02064359 0.01396152 0.00996428], RMS relative SE [0.02788479 0.02207465 0.02030004 0.01900087], pairwise [0.48942866 0.56423785 0.4866183 ] PASS §11 geometric Brownian Euler–Maruyama — order 0.5185, paired 95% [0.4936, 0.5448], band [0.4, 0.65], physverify PASS
§11 geometric Brownian Milstein: RMS [0.00252965 0.00121081 0.00062654 0.00031633], RMS relative SE [0.02882894 0.02210184 0.02754053 0.02386653], pairwise [1.06296975 0.9504859 0.98597134] PASS §11 geometric Brownian Milstein — order 0.9949, paired 95% [0.9670, 1.0225], band [0.85, 1.2], physverify PASS
Schemes · Drift order, noise regime and taming¶
With σ=0 the constant mode solves (u'=u-u^3) with exact solution (u(t)=[1+(u_0^{-2}-1)e^{-2t}]^{-1/2}). The weak and mean-square small-noise expansions of Milstein & Tretyakov motivate the separate drift and noise scales (weak, mean-square). At small additive noise the deterministic and stochastic RMS scales are (O(h^k)) and (O(\sigma h)). The predicted crossover h for k=2, 3 and 4 is 4.60237×10⁻⁶, 0.00311483 and 0.02872452. The frozen scalar forecasts combine the exact deterministic level differences with the centred tangent covariance of the pair. This gives a root-mean-square prediction of √(μ²+σ²V). The middle plot compares these derived curves with paired-bootstrap error bars and tests adjacent slopes at ±0.2 around the forecasts. At moderate noise the leading treatment sets the rate for this fixed grid. Taming perturbs the drift by O(h), capping accuracy against the original flow at first order. For the numerical treatment of non-globally Lipschitz drift, see Hutzenthaler & Jentzen (2015).
Benchmark on CPU, float64, N=64, M=32. Times in ms per 32-member step are medians over five compiled runs of 256 steps.
| Order | FFTs additive / multiplicative | Additive time | Euler–Maruyama time | Milstein time |
|---|---|---|---|---|
| 1 | 5 / 8 | 0.046837 | 0.070061 | 0.069411 |
| 2 | 7 / 10 | 0.055786 | 0.079655 | 0.077977 |
| 3 | 9 / 12 | 0.076932 | 0.088780 | 0.125911 |
| 4 | 11 / 14 | 0.090506 | 0.101586 | 0.100485 |
ORDERS = (1, 2, 3, 4)
T = 0.5
U0 = 0.65
N = 8
PATHS = 64 if SMOKE else 1536
BATCH = 64
DIFFUSIVITY = 0.05
def stochastic(order, dt, n=N, *, use_taming=False, **options):
return StochasticAllenCahn(
1,
1.0,
n,
dt,
order=order,
diffusivity=DIFFUSIVITY,
lambda_=1.0,
dealiasing_fraction=2 / 3,
use_taming=use_taming,
**options,
)
def deterministic(order, dt, n=N):
return ex.stepper.reaction.AllenCahn(
1,
1.0,
n,
dt,
order=order,
diffusivity=DIFFUSIVITY,
first_order_coefficient=1,
third_order_coefficient=-1,
dealiasing_fraction=2 / 3,
)
def coupled_scores(order, counts, seed, *, paths=PATHS, **noise):
"""Final scores only, with all level endpoints on one common path."""
if SMOKE:
paths = BATCH
steppers = tuple(stochastic(order, T / n, noise_alpha=12, **noise) for n in counts)
finest = steppers[-1]
block_size = counts[-1] // counts[0]
original = ex.fft(jnp.full((1, N), U0))
root = jax.random.key(seed)
@jax.jit
def compute(path_indices):
keys = jax.vmap(lambda i: jax.random.fold_in(root, i))(path_indices)
start = jnp.broadcast_to(original, (BATCH, *original.shape))
def block(states, index):
times = block_size * index + jnp.arange(block_size)
increments = jax.vmap(
lambda t: jax.vmap(
lambda key: finest.sample_increment(jax.random.fold_in(key, t))
)(keys)
)(times)
level_inputs = [increments]
for fine in reversed(steppers[1:]):
pairs = increments.reshape((-1, 2, BATCH, *original.shape))
coarsen = jax.vmap(fine.coarsen_increments, in_axes=1)
increments = jax.vmap(coarsen)(pairs)
level_inputs.append(increments)
def advance(stepper, initial, draws):
step = jax.vmap(stepper.step_with_increment)
return jax.lax.scan(lambda u, d: (step(u, d), None), initial, draws)[0]
return tuple(
advance(solver, u, draws)
for solver, u, draws in zip(
steppers, states, reversed(level_inputs), strict=True
)
), None
states, _ = jax.lax.scan(block, (start,) * len(counts), jnp.arange(counts[0]))
differences = jnp.stack(states[:-1]) - jnp.stack(states[1:])
physical = ex.ifft(differences, num_spatial_dims=1, num_points=N)
return jnp.mean(physical**2, axis=(-1, -2)), differences[..., 0, 0].real / N
batches = [
tuple(map(np.asarray, compute(jnp.arange(i, i + BATCH))))
for i in range(0, paths, BATCH)
]
return tuple(
np.concatenate(values, axis=-1) for values in zip(*batches, strict=True)
)
def bootstrap_means(squares, seed):
rng = np.random.default_rng(seed)
paths = squares.shape[-1]
return np.concatenate(
[
squares[..., rng.integers(paths, size=(32, paths))].mean(axis=-1)
for _ in range(32)
],
axis=-1,
)
LEVEL_BIAS = np.array(
[
[
7.82898495e-03,
3.69337148e-03,
1.79506319e-03,
8.85053506e-04,
4.39458853e-04,
],
[
1.40080077e-03,
3.15422913e-04,
7.49017568e-05,
1.82540306e-05,
4.50595712e-06,
],
[
7.50558913e-05,
8.95991341e-06,
1.09114042e-06,
1.34533306e-07,
1.66990101e-08,
],
[
4.06325212e-06,
2.34540500e-07,
1.40880835e-08,
8.63204730e-10,
5.34060574e-11,
],
]
)
TANGENT_VARIANCE = np.array(
[
[
2.302145278e-03,
5.045539643e-04,
1.182562912e-04,
2.863562353e-05,
7.046241578e-06,
],
[
2.417185784e-03,
5.427318294e-04,
1.284040921e-04,
3.121775435e-05,
7.695711754e-06,
],
[
2.423213193e-03,
5.427425953e-04,
1.283685001e-04,
3.121131580e-05,
7.694792570e-06,
],
[
2.419751601e-03,
5.425520981e-04,
1.283574903e-04,
3.121065612e-05,
7.694752229e-06,
],
]
)
counts = (4, 8, 16, 32)
hs = T / np.asarray(counts)
analytic = (1 + (U0**-2 - 1) * np.exp(-2 * T)) ** -0.5
ic = jnp.full((1, N), U0)
key = jax.random.key(4035)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
for k in (1, 4) if SMOKE else ORDERS:
for tame, ax in zip((False, True), axes, strict=True):
errors = []
for steps in counts:
solver = stochastic(k, T / steps, sigma=0.0, use_taming=tame)
endpoint = jax.jit(
lambda u, steps=steps, solver=solver, key=key: jax.lax.fori_loop(
0, steps, lambda _, current: solver(current, key=key), u
)
)(ic)
errors.append(abs(float(endpoint[0, 0]) - analytic))
expected = 1 if tame else k
fit = check_order(
hs, errors, expected, tol=0.2, floor=1e-14, scale=analytic, fit_points=4
)
record(
f"Schemes {'tamed' if tame else 'untamed'} order {k}",
fit.status,
fit.message,
)
(line,) = ax.loglog(hs, errors, ".-", label=f"k={k}")
ax.loglog(
hs, errors[-1] * (hs / hs[-1]) ** expected, "--", color=line.get_color()
)
grid = (
U0
+ 0.12 * jnp.cos(2 * jnp.pi * jnp.arange(16) / 16)
- 0.05 * jnp.sin(4 * jnp.pi * jnp.arange(16) / 16)
)[None]
solver = stochastic(k, 0.005, 16, sigma=0.0)
equal = paired_parity(
grid,
lambda u, solver=solver: solver(u, key=key),
deterministic(k, 0.005, 16),
20,
)
record(
f"Schemes upstream ETDRK{k} parity",
"PASS" if equal else "FAIL",
"one and 20 steps",
)
for ax, title in zip(axes, ("Untamed", "Tamed against untamed flow"), strict=True):
ax.set(title=title, xlabel="h", ylabel="Absolute error")
ax.legend()
figure(fig)
counts = (4, 8, 16, 32, 64, 128)
hs = T / np.array(counts[:-1])
small_sigma = 1e-6
squares = np.stack(
[coupled_scores(k, counts, 4036, sigma=small_sigma)[0] for k in ORDERS]
)
paired = bootstrap_means(squares, 4037)
variance = small_sigma**2 * TANGENT_VARIANCE
expected = LEVEL_BIAS**2 + variance
expected_se = np.sqrt((2 * variance**2 + 4 * LEVEL_BIAS**2 * variance) / PATHS)
mse = squares.mean(axis=-1)
rms = np.sqrt(mse)
boot_rms = np.sqrt(paired)
qlo, qhi = np.quantile(boot_rms, (0.025, 0.975), axis=-1)
ci = np.quantile(0.5 * np.log2(paired[:, :-1] / paired[:, 1:]), (0.025, 0.975), axis=-1)
predicted_slopes = 0.5 * np.log2(expected[:, :-1] / expected[:, 1:])
ranks = np.quantile(np.sqrt(paired[:-1] / paired[1:]), 0.025, axis=-1)
zmax = np.max(abs(mse - expected) / expected_se)
ok = (
zmax <= 5
and np.all(ci[0] >= predicted_slopes - 0.2)
and np.all(ci[1] <= predicted_slopes + 0.2)
and np.all(ranks > 1)
)
record(
"Schemes small-noise crossover",
"PASS" if ok else "FAIL",
f"order-4 h*=0.02872452, largest MSE deviation {zmax:.2f} SE, slope bands ±0.2",
)
print(f"Order-4 slopes {np.log2(rms[-1, :-1] / rms[-1, 1:])}, bounds {ci[:, -1]}")
fig, ax = plt.subplots()
for k in ORDERS:
i = k - 1
line = ax.errorbar(
hs, rms[i], yerr=[rms[i] - qlo[i], qhi[i] - rms[i]], fmt="o", label=f"k={k}"
)
ax.loglog(hs, np.sqrt(expected[i]), "-", color=line[0].get_color())
ax.loglog(hs, abs(LEVEL_BIAS[-1]), "k:", label="k=4 deterministic term")
ax.loglog(hs, np.sqrt(variance[-1]), "k--", label="k=4 stochastic term")
ax.axvline(0.02872452, color="0.7")
ax.set(xlabel="h", ylabel="Adjacent RMS")
ax.legend(fontsize=8)
figure(fig)
counts = (16, 32, 64, 128, 256)
hs = T / np.array(counts[:-1])
fig, axes = plt.subplots(1, 3, figsize=(12, 3.4))
for ax, (noise, milstein, orders, paths, expected, band) in zip(
axes,
(
("additive", False, ORDERS, 1536, 1, (0.8, 1.2)),
("multiplicative", False, (2, 4), 1536, 0.5, (0.35, 0.65)),
("multiplicative", True, (2, 4), 8192, 1, (0.8, 1.2)),
),
strict=True,
):
method = (
"additive"
if noise == "additive"
else "Milstein"
if milstein
else "Euler–Maruyama"
)
for k in orders[:1] if SMOKE else orders:
squares = coupled_scores(
k,
counts,
4038,
paths=paths,
sigma=0.35,
noise_type=noise,
use_milstein=milstein,
)[0]
errors = strong_order(
f"Schemes {method} k={k}", hs, squares, expected, band, 4039
)
(line,) = ax.loglog(hs, errors, ".-", label=f"k={k}")
ax.loglog(
hs, errors[-1] * (hs / hs[-1]) ** expected, "--", color=line.get_color()
)
ax.set(title=method, xlabel="h", ylabel="Adjacent RMS")
ax.legend()
figure(fig)
jax.clear_caches()
_ = gc.collect()
PASS Schemes untamed order 1 — observed order 1.03 (expected 1)
PASS Schemes tamed order 1 — observed order 1.02 (expected 1)
Maximum errors after one and 20 steps: 0, 0; bit-exact True PASS Schemes upstream ETDRK1 parity — one and 20 steps
PASS Schemes untamed order 2 — observed order 2.07 (expected 2)
/tmp/ipykernel_2742/1836201201.py:17: TamingOrderWarning: Taming changes the drift by O(h), so accuracy stays first order relative to the untamed model. return StochasticAllenCahn(
PASS Schemes tamed order 2 — observed order 0.91 (expected 1)
Maximum errors after one and 20 steps: 0, 0; bit-exact True PASS Schemes upstream ETDRK2 parity — one and 20 steps
PASS Schemes untamed order 3 — observed order 3.04 (expected 3)
PASS Schemes tamed order 3 — observed order 1.00 (expected 1)
Maximum errors after one and 20 steps: 0, 0; bit-exact True PASS Schemes upstream ETDRK3 parity — one and 20 steps
PASS Schemes untamed order 4 — observed order 4.06 (expected 4)
PASS Schemes tamed order 4 — observed order 0.99 (expected 1)
Maximum errors after one and 20 steps: 0, 0; bit-exact True PASS Schemes upstream ETDRK4 parity — one and 20 steps
PASS Schemes small-noise crossover — order-4 h*=0.02872452, largest MSE deviation 1.27 SE, slope bands ±0.2 Order-4 slopes [4.10793538 3.71633909 1.69923129 0.99795808], bounds [[4.10167608 3.6814955 1.64468417 0.9361611 ] [4.11443878 3.75517174 1.75944868 1.0554569 ]]
Schemes additive k=1: RMS [0.00407567 0.00207925 0.00097598 0.00049127], RMS relative SE [0.02173776 0.02153955 0.02134787 0.0203451 ], pairwise [0.97097702 1.09113246 0.99034393] PASS Schemes additive k=1 — order 1.0248, paired 95% [1.0026, 1.0459], band [0.8, 1.2], physverify PASS
Schemes additive k=2: RMS [0.00407009 0.00208589 0.00098417 0.0004904 ], RMS relative SE [0.02180323 0.02169044 0.02503729 0.0211933 ], pairwise [0.96440234 1.08368037 1.00493873] PASS Schemes additive k=2 — order 1.0243, paired 95% [1.0040, 1.0452], band [0.8, 1.2], physverify PASS
Schemes additive k=3: RMS [0.00405363 0.00208195 0.00098306 0.00049017], RMS relative SE [0.02176578 0.02164645 0.02493508 0.0211793 ], pairwise [0.96127647 1.08258781 1.0039844 ] PASS Schemes additive k=3 — order 1.0226, paired 95% [1.0021, 1.0437], band [0.8, 1.2], physverify PASS
Schemes additive k=4: RMS [0.0040541 0.00208201 0.00098307 0.00049017], RMS relative SE [0.02176923 0.02164791 0.02493624 0.02117939], pairwise [0.96140611 1.08261415 1.0039938 ] PASS Schemes additive k=4 — order 1.0227, paired 95% [1.0022, 1.0437], band [0.8, 1.2], physverify PASS
Schemes Euler–Maruyama k=2: RMS [0.00615321 0.00399667 0.00254106 0.00177919], RMS relative SE [0.01959024 0.0197297 0.01899387 0.02003124], pairwise [0.62254044 0.65336693 0.51421447] PASS Schemes Euler–Maruyama k=2 — order 0.6024, paired 95% [0.5778, 0.6261], band [0.35, 0.65], physverify PASS
Schemes Euler–Maruyama k=4: RMS [0.00614702 0.00399563 0.00254072 0.00177916], RMS relative SE [0.01961899 0.0197069 0.01899441 0.02002578], pairwise [0.6214625 0.65318569 0.51403998] PASS Schemes Euler–Maruyama k=4 — order 0.6019, paired 95% [0.5771, 0.6256], band [0.35, 0.65], physverify PASS
Schemes Milstein k=2: RMS [0.00370886 0.00181898 0.0009003 0.00044212], RMS relative SE [0.01685842 0.01794775 0.01882204 0.01825269], pairwise [1.02784555 1.01465734 1.02596803] PASS Schemes Milstein k=2 — order 1.0220, paired 95% [1.0119, 1.0323], band [0.8, 1.2], physverify PASS
Schemes Milstein k=4: RMS [0.00369507 0.00181567 0.00089946 0.00044191], RMS relative SE [0.01672741 0.01786543 0.01875783 0.01823403], pairwise [1.02509701 1.01336469 1.02532068] PASS Schemes Milstein k=4 — order 1.0205, paired 95% [1.0103, 1.0309], band [0.8, 1.2], physverify PASS
12 · Nonlinear weak Richardson comparison¶
The terminal observable is mean(u)². At σ=0.02 the weak bias is drift-dominated, with noise contributing O(σ²h) in the small-noise expansion. At σ=0 the squared-observable biases relative to the exact constant-mode flow are 0.0118811919, 0.0058157296 and 0.0028776280 at 8, 16 and 32 steps. Estimate the nonzero-noise weak bias with the independent T/512 reference, run by default. In the λ=0 Gaussian control the exact squared-mean expectation is u₀²+σ²T for the unit period.
Use the original 512-path CVs with a 90% power margin, replacing five by 5+1.28 in the count calculation. Round up to a 64-path batch and use fresh keys. Report the coupled sampler first and the independent sampler alongside it. A signal below five SEs is inconclusive.
For the extrapolated residual use all four levels on one Brownian path
with increments drawn at T/1024. The difference is (2F−C)−(2R₂−R₁),
where R₁ and R₂ use T/512 and T/1024. The scalar ETDRK1 map predicts
−2.4968e−4 and −6.0416e−5 for c=8 and c=16. The corresponding noise
correction is O(σ²h²). For these must-pass rows, use the archived pilot CVs
and 99.9% power at five SE, with 1,024 and 4,160 paths and fresh keys.
The four-level λ=0 check compares each Fourier mode on every path and
retains the exact marginal test. For nonzero reaction, see the tests of
coarsened increment covariance
in test_coarsened_increment_covariance.
def weak_step(count, reaction=1.0):
return StochasticAllenCahn(
1,
1.0,
8,
0.5 / count,
diffusivity=0.05,
lambda_=reaction,
noise_alpha=12,
sigma=0.02,
order=1,
use_taming=False,
)
def terminal_stat(step, u0, count, seed, paths, observable):
advance = jax.jit(lambda u, key: step(u, key=key))
def member(key):
def inner(i, u):
return advance(u, jax.random.fold_in(key, i))
return observable(jax.lax.fori_loop(0, count, inner, u0))
def run(keys):
return jax.lax.map(member, keys, batch_size=64)
keys = jax.random.split(jax.random.key(seed), paths)
return np.asarray(jax.jit(run)(keys))
def mean_squared(u):
return jnp.mean(u) ** 2
# Power-margin counts from the archived pilot CVs. Production keys are fresh.
production = {8: (1024, 18320, 18322), 16: (4160, 18321, 18323)}
reference_count, reference_seed, null_seed = 4160, 18324, 18325
if SMOKE:
reference_count = 64
production = {count: (64, p, i) for count, (_, p, i) in production.items()}
u0 = jnp.full((1, 8), 0.65)
ref = terminal_stat(
weak_step(512), u0, 512, reference_seed, reference_count, mean_squared
)
reference = ref.mean()
reference_se = ref.std(ddof=1) / np.sqrt(reference_count)
print(f"Independent stochastic T/512 reference {reference:.9f} ± {reference_se:.3g} SE")
print("steps | sampler | coarse ± SE | fine ± SE | rich ± SE | fine−coarse ± SE")
for count, (samples, paired_seed, independent_seed) in production.items():
coarse, fine = weak_step(count), weak_step(2 * count)
for paired, seed in ((True, paired_seed), (False, independent_seed)):
v = spde.richardson_weak_extrapolation(
coarse,
fine,
u0,
count,
jax.random.key(seed),
num_samples=samples,
batch_size=64,
observable=mean_squared,
coupled=paired,
weak_order=1.0,
)
values = " | ".join(
f"{float(v[f'mean_{q}']):.8f} ± {float(v[f'se_{q}']):.3g}"
for q in ("coarse", "fine", "rich")
)
delta = float(v["mean_fine"] - v["mean_coarse"])
print(
f"{count} | {'coupled' if paired else 'independent'} | {values} | "
f"{delta:+.8f} ± {float(v['se_difference']):.3g}"
)
reference_z = abs(float(v["mean_fine"]) - reference) / np.hypot(
float(v["se_fine"]), reference_se
)
rich_z = abs(float(v["mean_rich"]) - reference) / np.hypot(
float(v["se_rich"]), reference_se
)
delta_z = abs(delta) / float(v["se_difference"])
record(
f"§12 {'coupled' if paired else 'independent'} weak signal, coarse {count}",
"PASS" if min(reference_z, delta_z) >= 5 else "INCONCLUSIVE",
f"coarse–fine {delta_z:.2f} SE, fine–reference {reference_z:.2f} SE",
)
print(
f"Extrapolated residual versus reference is {rich_z:.2f} SE; "
f"{'unresolved' if rich_z < 5 else 'resolved'} at five SE"
)
null_keys = jax.random.split(jax.random.key(null_seed), 2)
target = 0.65**2 + 0.02**2 * 0.5
zmax, null_gap = 0.0, 0.0
for paired, seed in zip((True, False), null_keys, strict=True):
v = spde.richardson_weak_extrapolation(
weak_step(8, reaction=0),
weak_step(16, reaction=0),
u0,
8,
seed,
num_samples=reference_count,
batch_size=64,
observable=mean_squared,
coupled=paired,
)
for tag in ("coarse", "fine", "rich"):
zmax = max(zmax, abs(float(v[f"mean_{tag}"]) - target) / float(v[f"se_{tag}"]))
if paired:
null_gap = abs(float(v["mean_fine"] - v["mean_coarse"]))
print(
f"λ=0 {'coupled' if paired else 'independent'} exact mean {target:.7f}, "
f"estimate {float(v['mean_rich']):.8f} ± {float(v['se_rich']):.3g}, "
f"difference SE {float(v['se_difference']):.3g}"
)
record(
"§12 exact Gaussian null",
"PASS" if null_gap < 1e-12 and zmax <= 5 else "FAIL",
f"coupled gap {null_gap:.3g}, max discrepancy {zmax:.2f} SE",
)
def residual_levels(coarse_count, seed, paths, reaction=1.0):
"""Return terminal Fourier states on each shared path."""
levels = (coarse_count, 2 * coarse_count, 512, 1024)
models = tuple(weak_step(count, reaction=reaction) for count in levels)
fine = models[-1]
batch = 64
block_size = 1024 // coarse_count
start = jnp.broadcast_to(ex.fft(jnp.full((1, 8), 0.65)), (batch, 1, 5))
draw = jax.vmap(jax.vmap(fine.sample_increment))
coarsen = jax.vmap(jax.vmap(fine.coarsen_increments, in_axes=1))
steppers = tuple(jax.vmap(solver.step_with_increment) for solver in models)
@jax.jit
def sample(root):
def advance(states, index):
keys = jax.random.split(
jax.random.fold_in(root, index), (block_size, batch)
)
increments = draw(keys)
fields = []
for count, step, state in zip(levels, steppers, states, strict=True):
ratio = 1024 // count
dws = increments
if ratio > 1:
dws = coarsen(increments.reshape(-1, ratio, *increments.shape[1:]))
end = jax.lax.scan(
lambda u, inc, step=step: (step(u, inc), None), state, dws
)[0]
fields.append(end)
return tuple(fields), None
fields, _ = jax.lax.scan(
advance, (start,) * len(levels), jnp.arange(coarse_count)
)
return jnp.stack(fields)
root = jax.random.key(seed)
chunks = [
np.asarray(sample(jax.random.fold_in(root, i))) for i in range(paths // batch)
]
return np.concatenate(chunks, axis=1)
def residual(samples):
coarse, fine, ref1, ref2 = samples
return (2 * fine - coarse) - (2 * ref2 - ref1)
residual_plan = [(8, 1024, 19328, -0.00024968), (16, 4160, 19329, -6.0416e-05)]
zmax, same_path = 0.0, 0.0
for count, _, _, _ in residual_plan:
null_paths = 64 if SMOKE else 512
fields = residual_levels(count, 18330, null_paths, reaction=0.0)
gaps = np.max(abs(fields[:, None] - fields[None, :]), axis=(0, 1, 3, 4))
scale = np.max(abs(fields), axis=(0, 2, 3))
same_path = max(same_path, float(np.max(gaps / scale)))
values = np.square(fields[:, :, 0, 0].real / 8)
se = values.std(axis=1, ddof=1) / np.sqrt(null_paths)
zmax = max(zmax, float(np.max(abs(values.mean(axis=1) - target) / se)))
record(
"§12 exact four-level Gaussian marginals",
"PASS" if same_path <= 1e-12 and zmax <= 5 else "FAIL",
f"largest relative Fourier gap {same_path:.3g}, marginal discrepancy {zmax:.2f} SE",
)
measured = []
for count, size, seed, prediction in residual_plan:
size = 64 if SMOKE else size
fields = residual_levels(count, seed, size)
d = residual(np.square(fields[:, :, 0, 0].real / 8))
mean = float(d.mean())
se = float(d.std(ddof=1) / np.sqrt(size))
agreement = abs(mean - prediction) / se
detection = abs(mean) / se
status = "FAIL" if agreement > 5 else "PASS" if detection >= 5 else "INCONCLUSIVE"
record(
f"§12 coupled four-level residual c={count}",
status,
f"mean {mean:+.9g}, SE {se:.3g}, predicted {prediction:+.7g}, "
f"agreement {agreement:.2f} SE, detection {detection:.2f} SE, M={size}",
)
measured.append((mean, se))
(a, se_a), (b, se_b) = measured
ratio = a / b
ratio_se = np.hypot(se_a / b, a * se_b / b**2)
print(f"Residual ratio {ratio:.4f} ± {ratio_se:.3g} delta-method SE (forecast 4.13)")
jax.clear_caches()
_ = gc.collect()
Independent stochastic T/512 reference 0.665579209 ± 0.000297 SE steps | sampler | coarse ± SE | fine ± SE | rich ± SE | fine−coarse ± SE
8 | coupled | 0.67726009 ± 0.000631 | 0.67117378 ± 0.000613 | 0.66508747 ± 0.000595 | -0.00608631 ± 2.47e-05 PASS §12 coupled weak signal, coarse 8 — coarse–fine 245.97 SE, fine–reference 8.22 SE Extrapolated residual versus reference is 0.74 SE; unresolved at five SE
8 | independent | 0.67735029 ± 0.000638 | 0.67167502 ± 0.000612 | 0.66599976 ± 0.00138 | -0.00567527 ± 0.000884 PASS §12 independent weak signal, coarse 8 — coarse–fine 6.42 SE, fine–reference 8.96 SE Extrapolated residual versus reference is 0.30 SE; unresolved at five SE
16 | coupled | 0.67155361 ± 0.000303 | 0.66860619 ± 0.000298 | 0.66565876 ± 0.000294 | -0.00294742 ± 6e-06 PASS §12 coupled weak signal, coarse 16 — coarse–fine 490.89 SE, fine–reference 7.19 SE Extrapolated residual versus reference is 0.19 SE; unresolved at five SE
16 | independent | 0.67107190 ± 0.000307 | 0.66883613 ± 0.000299 | 0.66660035 ± 0.000673 | -0.00223578 ± 0.000429 PASS §12 independent weak signal, coarse 16 — coarse–fine 5.21 SE, fine–reference 7.73 SE Extrapolated residual versus reference is 1.39 SE; unresolved at five SE
λ=0 coupled exact mean 0.4227000, estimate 0.42245373 ± 0.00029, difference SE 3.43e-18
λ=0 independent exact mean 0.4227000, estimate 0.42332465 ± 0.000635, difference SE 0.000403 PASS §12 exact Gaussian null — coupled gap 0, max discrepancy 1.21 SE
PASS §12 exact four-level Gaussian marginals — largest relative Fourier gap 6.42e-15, marginal discrepancy 0.73 SE
PASS §12 coupled four-level residual c=8 — mean -0.000245444639, SE 1.94e-05, predicted -0.00024968, agreement 0.22 SE, detection 12.64 SE, M=1024
PASS §12 coupled four-level residual c=16 — mean -6.46527335e-05, SE 4.65e-06, predicted -6.0416e-05, agreement 0.91 SE, detection 13.90 SE, M=4160 Residual ratio 3.7964 ± 0.406 delta-method SE (forecast 4.13)
13 · Host-side Strang scaffold¶
Use a continuous OU source as a stand-in for the shaped host increment. Compose half OU, spectral step and half OU with the low-pass-filtered increments. Verify the composition against an explicit NumPy Fourier mask. Use the same spectral keys in both trajectories. Check the source separately against its exact Gaussian half-step mean and variance. This demonstration does not implement the full hybrid or two-regime algorithms.
n, h, theta, mu, eta = 128, 0.0005, 5, -0.3, 0.15
step = model(1, n, h, nu=0.01, sigma=0.15, use_taming=True)
compiled_step = jax.jit(lambda u, *, key: step(u, key=key))
initial = 0.3 + 0.05 * grf(1, n, 100, zero_mean=True)
decay = math.exp(-theta * h / 2)
sd = eta * math.sqrt(-math.expm1(-theta * h) / (2 * theta))
def ou_half(state, half_dt):
value, rng = state["value"], state["rng"]
decay = math.exp(-theta * half_dt)
scale = eta * math.sqrt(-math.expm1(-2 * theta * half_dt) / (2 * theta))
new = mu + decay * (value - mu) + scale * rng.standard_normal(value.shape)
return {"value": new, "rng": rng, "delta_concentration": new - value}
def fixed_half(state, _):
return {"delta_concentration": state["delta_concentration"]}
def explicit_mollify(delta):
filt = np.arange(n // 2 + 1) <= n // 4
return np.fft.irfft(filt * np.fft.rfft(delta), n=n)
delta = np.asarray((0.01 * jnp.cos(2 * jnp.pi * jnp.arange(n) / n))[None])
check_key = jax.random.key(229)
observed, _ = spde.strang_split_step(
compiled_step,
fixed_half,
initial,
{"delta_concentration": delta},
h,
check_key,
num_points=n,
)
expected = compiled_step(
initial + explicit_mollify(delta), key=jax.random.split(check_key)[1]
)
residual = float(jnp.max(abs(observed - (expected + explicit_mollify(delta)))))
record(
"§13 split composition",
"PASS" if residual < 1e-12 else "FAIL",
f"max error {residual:.3g}",
)
rng = np.random.default_rng(42)
state = {"value": np.full((1, n), 0.3), "rng": rng}
pde = hybrid = initial
paths_pde, paths_hybrid = [np.asarray(initial)[0]], [np.asarray(initial)[0]]
for index in range(1000):
key = jax.random.fold_in(jax.random.key(102), index)
pde = compiled_step(pde, key=jax.random.split(key)[1])
hybrid, state = spde.strang_split_step(
compiled_step,
ou_half,
hybrid,
state,
h,
key,
num_points=n,
)
if (index + 1) % 5 == 0:
paths_pde.append(np.asarray(pde)[0])
paths_hybrid.append(np.asarray(hybrid)[0])
fig, axes = plt.subplots(1, 2, figsize=(9, 3))
for ax, fields, label in zip(
axes, (paths_pde, paths_hybrid), ("PDE", "PDE + host OU"), strict=True
):
im = ax.imshow(
fields,
aspect="auto",
origin="lower",
extent=(0, 1, 0, 0.5),
cmap="RdBu_r",
vmin=-1,
vmax=1,
)
ax.set(title=label, xlabel="Position", ylabel="Time")
figure(fig)
# For the source alone, test a half-step from a fixed concentration.
samples = ou_half(
{"value": np.full((1, 8192), 0.3), "rng": np.random.default_rng(230)}, h / 2
)["value"]
mean_exact = mu + decay * (0.3 - mu)
variance_exact = sd**2
var = samples.var(ddof=1)
mean_z = abs(samples.mean() - mean_exact) / (sd / np.sqrt(samples.size))
se_variance = ((samples - samples.mean()) ** 2).std(ddof=1) / np.sqrt(samples.size)
var_z = abs(var - variance_exact) / se_variance
record(
"§13 exact OU half-step",
"PASS" if max(mean_z, var_z) <= 5 else "FAIL",
f"mean={samples.mean():.8f} (target {mean_exact:.8f}), "
f"var={var:.5g} (target {variance_exact:.5g}), max {max(mean_z, var_z):.2f} SE",
)
jax.clear_caches()
_ = gc.collect()
PASS §13 split composition — max error 1.67e-16
PASS §13 exact OU half-step — mean=0.29924859 (target 0.29925047), var=5.6321e-06 (target 5.618e-06), max 0.16 SE
14 · Verdicts¶
Record a host-side physverify verdict for each spectral family, supplying the mean, independent-group SE, exact reference, a 10% resolution, and degrees of freedom. Use the predeclared order tolerances and paired-bootstrap intervals for convergence. Unresolved weak effects and spectrum comparisons can be inconclusive. A FAIL stops validation.
for label, modes in spectral_comparisons:
v = verdict(modes, alpha=0.001)
record(label, v.status, f"{modes[0].dof + 1} groups. {v.message}")
runtime = ", ".join(
f"{name} {version(name)}"
for name in ("jax", "jaxlib", "numpy", "exponax", "exponax-spde")
)
results.sort(
key=lambda row: 11.5 if row[0].startswith("Schemes") else int(row[0].split()[0][1:])
)
lines = [
"# Stochastic Allen–Cahn validation",
"",
f"{provenance} · {date.today().isoformat()} · "
f"Python {platform.python_version()}, {runtime} · CPU float64.",
"",
"PASS meets the gate · INCONCLUSIVE leaves a signal or resolution unresolved · "
"DIAGNOSTIC is descriptive · FAIL misses the gate.",
"",
"| Check | Verdict | Evidence |",
"| --- | --- | --- |",
]
lines.extend(
f"| {label} | {status} | {description.replace('|', '/')} |"
for label, status, description in results
)
assert all(len(row.splitlines()) == 1 for row in lines if row.startswith("|"))
table = "\n".join(lines) + "\n"
if not SMOKE:
(OUTPUT / "validation_summary.md").write_text(table, encoding="utf-8")
display(Markdown(table))
counts_by_status = {
status: sum(r[1] == status for r in results)
for status in ("PASS", "INCONCLUSIVE", "DIAGNOSTIC", "FAIL")
}
print(provenance)
print(counts_by_status)
if counts_by_status["FAIL"]:
raise RuntimeError(
"A §14 verdict failed. Preserve the run and diagnose the failure."
)
jax.clear_caches()
_ = gc.collect()
PASS §2 h=0.001 — 90 groups. all 3 comparisons agree; largest: §2 h=0.001 mode (3,) = 2.1041e-06 +- 1.5e-08, exact 2.0923e-06 (Bonferroni over 3, false-alarm rate 0.001) PASS §2 h=0.002 — 77 groups. all 3 comparisons agree; largest: §2 h=0.002 mode (3,) = 2.1056e-06 +- 1.4e-08, exact 2.0923e-06 (Bonferroni over 3, false-alarm rate 0.001) PASS §3 axes and interior — 142 groups. all 4 comparisons agree; largest: §3 axes and interior mode (1, 0) = 0.00051031 +- 9.9e-06, exact 0.00049178 (Bonferroni over 4, false-alarm rate 0.001) PASS §4 alpha=0 — 178 groups. all 3 comparisons agree; largest: §4 alpha=0 mode (16,) = 0.00036372 +- 6.4e-06, exact 0.00035621 (Bonferroni over 3, false-alarm rate 0.001) PASS §4 alpha=1 — 124 groups. all 3 comparisons agree; largest: §4 alpha=1 mode (4,) = 9.1709e-06 +- 2.1e-07, exact 9.0086e-06 (Bonferroni over 3, false-alarm rate 0.001) PASS §4 alpha=2 — 143 groups. all 3 comparisons agree; largest: §4 alpha=2 mode (1,) = 5.5334e-05 +- 1.1e-06, exact 5.5505e-05 (Bonferroni over 3, false-alarm rate 0.001) PASS §4 alpha=3 — 147 groups. all 3 comparisons agree; largest: §4 alpha=3 mode (1,) = 1.3595e-06 +- 2.3e-08, exact 1.3712e-06 (Bonferroni over 3, false-alarm rate 0.001)
Stochastic Allen–Cahn validation¶
Executed commit 4120e8472db9ed0a2732cf77b7c51b09e38f84ea · executed library tree 2807c0a9d22cf4253d606adfd9e332ba484e1f40 · library clean · notebook source commit 6647f67c765229c817610368c67eca76a44987ff · 2026-11-30 · Python 3.13.18, jax 0.12.1, jaxlib 0.12.1, numpy 2.5.5, exponax 0.2.1, exponax-spde 0.5.0.dev0 · CPU float64.
PASS meets the gate · INCONCLUSIVE leaves a signal or resolution unresolved · DIAGNOSTIC is descriptive · FAIL misses the gate.
| Check | Verdict | Evidence |
|---|---|---|
| §1 deterministic parity | PASS | bit-exact physical=True, Fourier=True, 1–50 steps |
| §2 h=0.001 | PASS | 90 groups. all 3 comparisons agree; largest: §2 h=0.001 mode (3,) = 2.1041e-06 +- 1.5e-08, exact 2.0923e-06 (Bonferroni over 3, false-alarm rate 0.001) |
| §2 h=0.002 | PASS | 77 groups. all 3 comparisons agree; largest: §2 h=0.002 mode (3,) = 2.1056e-06 +- 1.4e-08, exact 2.0923e-06 (Bonferroni over 3, false-alarm rate 0.001) |
| §3 axes and interior | PASS | 142 groups. all 4 comparisons agree; largest: §3 axes and interior mode (1, 0) = 0.00051031 +- 9.9e-06, exact 0.00049178 (Bonferroni over 4, false-alarm rate 0.001) |
| §4 alpha=0 | PASS | 178 groups. all 3 comparisons agree; largest: §4 alpha=0 mode (16,) = 0.00036372 +- 6.4e-06, exact 0.00035621 (Bonferroni over 3, false-alarm rate 0.001) |
| §4 alpha=1 | PASS | 124 groups. all 3 comparisons agree; largest: §4 alpha=1 mode (4,) = 9.1709e-06 +- 2.1e-07, exact 9.0086e-06 (Bonferroni over 3, false-alarm rate 0.001) |
| §4 alpha=2 | PASS | 143 groups. all 3 comparisons agree; largest: §4 alpha=2 mode (1,) = 5.5334e-05 +- 1.1e-06, exact 5.5505e-05 (Bonferroni over 3, false-alarm rate 0.001) |
| §4 alpha=3 | PASS | 147 groups. all 3 comparisons agree; largest: §4 alpha=3 mode (1,) = 1.3595e-06 +- 2.3e-08, exact 1.3712e-06 (Bonferroni over 3, false-alarm rate 0.001) |
| §5 conditional kick moments | PASS | worst 0.308 SE, five-SE two-sided band |
| §8 radial PSD normalisation | PASS | max Parseval residual 2.22e-16 |
| §10 exact OU coupling | PASS | max Fourier difference 9.93e-16 |
| §10 additive fixed-grid order | PASS | order 0.9797, paired 95% [0.9577, 0.9996], band [0.75, 1.25], physverify PASS |
| §11 N=64 Euler–Maruyama | DIAGNOSTIC | order 0.4914, paired 95% [0.4614, 0.5231] |
| §11 N=64 Milstein | DIAGNOSTIC | order 0.9835, paired 95% [0.9789, 0.9884] |
| §11 #20 N=32 Euler–Maruyama | PASS | order 0.5170, paired 95% [0.5071, 0.5277], band [0.35, 0.7], physverify PASS |
| §11 #20 N=32 Milstein | PASS | order 1.0082, paired 95% [0.9980, 1.0190], band [0.8, 1.25], physverify PASS |
| §11 geometric Brownian Euler–Maruyama | PASS | order 0.5185, paired 95% [0.4936, 0.5448], band [0.4, 0.65], physverify PASS |
| §11 geometric Brownian Milstein | PASS | order 0.9949, paired 95% [0.9670, 1.0225], band [0.85, 1.2], physverify PASS |
| Schemes untamed order 1 | PASS | observed order 1.03 (expected 1) |
| Schemes tamed order 1 | PASS | observed order 1.02 (expected 1) |
| Schemes upstream ETDRK1 parity | PASS | one and 20 steps |
| Schemes untamed order 2 | PASS | observed order 2.07 (expected 2) |
| Schemes tamed order 2 | PASS | observed order 0.91 (expected 1) |
| Schemes upstream ETDRK2 parity | PASS | one and 20 steps |
| Schemes untamed order 3 | PASS | observed order 3.04 (expected 3) |
| Schemes tamed order 3 | PASS | observed order 1.00 (expected 1) |
| Schemes upstream ETDRK3 parity | PASS | one and 20 steps |
| Schemes untamed order 4 | PASS | observed order 4.06 (expected 4) |
| Schemes tamed order 4 | PASS | observed order 0.99 (expected 1) |
| Schemes upstream ETDRK4 parity | PASS | one and 20 steps |
| Schemes small-noise crossover | PASS | order-4 h*=0.02872452, largest MSE deviation 1.27 SE, slope bands ±0.2 |
| Schemes additive k=1 | PASS | order 1.0248, paired 95% [1.0026, 1.0459], band [0.8, 1.2], physverify PASS |
| Schemes additive k=2 | PASS | order 1.0243, paired 95% [1.0040, 1.0452], band [0.8, 1.2], physverify PASS |
| Schemes additive k=3 | PASS | order 1.0226, paired 95% [1.0021, 1.0437], band [0.8, 1.2], physverify PASS |
| Schemes additive k=4 | PASS | order 1.0227, paired 95% [1.0022, 1.0437], band [0.8, 1.2], physverify PASS |
| Schemes Euler–Maruyama k=2 | PASS | order 0.6024, paired 95% [0.5778, 0.6261], band [0.35, 0.65], physverify PASS |
| Schemes Euler–Maruyama k=4 | PASS | order 0.6019, paired 95% [0.5771, 0.6256], band [0.35, 0.65], physverify PASS |
| Schemes Milstein k=2 | PASS | order 1.0220, paired 95% [1.0119, 1.0323], band [0.8, 1.2], physverify PASS |
| Schemes Milstein k=4 | PASS | order 1.0205, paired 95% [1.0103, 1.0309], band [0.8, 1.2], physverify PASS |
| §12 coupled weak signal, coarse 8 | PASS | coarse–fine 245.97 SE, fine–reference 8.22 SE |
| §12 independent weak signal, coarse 8 | PASS | coarse–fine 6.42 SE, fine–reference 8.96 SE |
| §12 coupled weak signal, coarse 16 | PASS | coarse–fine 490.89 SE, fine–reference 7.19 SE |
| §12 independent weak signal, coarse 16 | PASS | coarse–fine 5.21 SE, fine–reference 7.73 SE |
| §12 exact Gaussian null | PASS | coupled gap 0, max discrepancy 1.21 SE |
| §12 exact four-level Gaussian marginals | PASS | largest relative Fourier gap 6.42e-15, marginal discrepancy 0.73 SE |
| §12 coupled four-level residual c=8 | PASS | mean -0.000245444639, SE 1.94e-05, predicted -0.00024968, agreement 0.22 SE, detection 12.64 SE, M=1024 |
| §12 coupled four-level residual c=16 | PASS | mean -6.46527335e-05, SE 4.65e-06, predicted -6.0416e-05, agreement 0.91 SE, detection 13.90 SE, M=4160 |
| §13 split composition | PASS | max error 1.67e-16 |
| §13 exact OU half-step | PASS | mean=0.29924859 (target 0.29925047), var=5.6321e-06 (target 5.618e-06), max 0.16 SE |
Executed commit `4120e8472db9ed0a2732cf77b7c51b09e38f84ea` · executed library tree `2807c0a9d22cf4253d606adfd9e332ba484e1f40` · library clean · notebook source commit `6647f67c765229c817610368c67eca76a44987ff`
{'PASS': 47, 'INCONCLUSIVE': 0, 'DIAGNOSTIC': 2, 'FAIL': 0}
References¶
- Allen & Cahn (1979) describe phase-field coarsening.
- Lord, Powell & Shardlow (2014) introduce computational SPDEs.
- Jentzen & Kloeden (2009) treat additive stochastic approximations.
- Kloeden & Platen (1992) treat scalar SDEs and their numerical approximations.
- Hutzenthaler & Jentzen (2015) treat non-globally Lipschitz coefficients.
- Milstein & Tretyakov (1997) derive weak and mean-square small-noise estimates.
- Hairer, Ryser & Weber (2012) analyse the 2-D continuum regularisation.
- Koehler et al. (2024), APEBench provides the exponax solver context.
- Cox & Matthews (2002) and Kassam & Trefethen (2005) describe exponential time differencing.
- Jentzen & Röckner (2015) describe the Milstein method for SPDEs. Lord & Tambue (2013) treat stochastic exponential integrators.
- Higham (2001) and Giles (2008) provide background on strong errors and coupled samples.
- Talay & Tubaro (1990) analyse weak-error expansions.
- Strang (1968) describes symmetric splitting.
- Harrison & Yates (2016) and Flegg et al. (2012) provide context for hybrid modelling. Gillespie (1977) is the SSA reference.
- Funaki (1995) studies scaling and phase separation under stochastic forcing.
- Bray (1994) reviews curvature-driven phase ordering.