Cahn–Hilliard nucleation on a bounded square¶
These simulations use the scalar additive noise of Blömker, Sander & Wanner (2016) on the unit Neumann square. The historical Cook model uses flux noise. Here \(q\) is the scalar spectrum in equation (2.1) with its constant mode removed. The initial concentration is the constant \(\mu=-0.59\).
| Parameter | Paper preset | Smoke preset |
|---|---|---|
| Side length, cell centres per axis | 1, 512 | 1/4, 128 |
| \(\varepsilon\), \(\gamma\) | 0.005, \(\varepsilon^2\) | same |
| \(\nu\), \(c_1\), \(c_3\), \(\mu\) | 1, −1, 1, −0.59 | same |
| Nonlinear cosine indices | 0–255 per axis | 0–63 per axis |
| Noise coordinates | Unnormalised products | Orthonormal |
| White \(\sigma\) | 0.05 | 0.025 |
| Band \(\sigma\), index radii | 1, \((10.5,11.5)\) | 0.5, \((10.5,11.5)\) |
| Single-mode \(\sigma\), indices | 5, (10,10), (15,15), (18,17) | 2.5, same indices |
The paper preset uses the observation times of Figs. 1, 3 and 6.
Section 2.3 gives 256 cosine indices, 512² evaluation points and a
step near \(5\times10^{-7}\). Output times are rounded to the nearest
fixed step. Set PAPER_STEP=True to use exactly \(5\times10^{-7}\).
Runtime depends on the machine. The smoke preset shares the paper
grid spacing but uses a short horizon for the test suite. Its
orthonormal white intensity matches the paper's interior coefficient
intensity because each unit-square cosine product has norm \(1/2\).
The previous \(\varepsilon=0.02\) illustration was withdrawn. Its white, sensitivity and band snapshots showed no nucleation, and mode (8,7) reached neither threshold. At fixed concentration the two-dimensional critical-nucleus energy scales roughly as \(\varepsilon^2\): rescaling space by the interface width gives the area factor. The (8,7) lobes are only a few interface widths across at the larger \(\varepsilon\), leaving little room for a nucleus.
We use exponential Euler on a cell-centred cosine grid. Hartley & Wanner (2009) use a semi-implicit spectral method. The continuum equation and noise law agree, so comparisons are statistical. The plots below come from these simulations.
Step-size bracket¶
For a frozen linearisation at concentration \(U\), a retained mode with \(\kappa=|k|^2\) has amplification \(g=\exp(hL)+h\varphi_1(hL)\lambda\) with \(L=\kappa(1-\varepsilon^2\kappa)\) and \(\lambda=-3U^2\kappa\).
The paper preset's default step is selected by coupling fine increments
with steps two and four times as long. The eight-seed comparison uses
the four white-noise snapshots and both single-mode threshold frames.
The largest admissible step changes each fractional count by at most
the larger of one component and 5%. This comparison shares the same
Brownian path. A standalone run draws one kick per step, so changing
the step changes the path even with the same key. Use PAPER_STEP=True
to replay the canonical-step comparison. The deterministic sweep below
starts from a small perturbation near the frozen limiting mode.
def stability_trial(h):
limit, mode = frozen_limit(M, 1.0)
model = make_stepper(M, h, spde.noise.Modes([mode]), 0.0, extent=EXTENT)
start = model.to_coefficients(jnp.asarray(1 + 1e-9 * cosine_mode(M, *mode))[None])
zero = jnp.zeros_like(start)
steps = int(np.ceil(200 * limit / h))
evolve = jax.jit(
lambda c: jax.lax.fori_loop(
0, steps, lambda _, v: model.step_with_increment(v, zero), c
)
)
field = np.asarray(model.to_physical(evolve(start)))
peak = float(np.max(abs(field)))
return bool(np.isfinite(peak) and peak <= 2.0), peak
sweep = []
for factor in (1, 2, 3, 4, 6, 8, 12, 16, 24, 32):
h = 5e-7 * factor
stable, peak = stability_trial(h)
sweep.append((h, stable, peak))
print(f"stability h={h:.8g} stable={stable} max_abs={peak:.7g}")
if not stable:
break
assert len(sweep) >= 2 and sweep[-2][1] and not sweep[-1][1]
largest_stable_h, first_unstable_h = sweep[-2][0], sweep[-1][0]
print(f"stability bracket [{largest_stable_h:.8g}, {first_unstable_h:.8g}]")
stability h=5e-07 stable=True max_abs=1
stability h=1e-06 stable=True max_abs=1
stability h=1.5e-06 stable=True max_abs=1
stability h=2e-06 stable=True max_abs=1
stability h=3e-06 stable=True max_abs=1
stability h=4e-06 stable=True max_abs=1
stability h=6e-06 stable=True max_abs=1
stability h=8e-06 stable=True max_abs=1.089287
stability h=1.2e-05 stable=False max_abs=nan stability bracket [8e-06, 1.2e-05]
Excited mode counts¶
The eigenvalues on the unit square use \(\pi(j,k)\), as on the side-two periodic mirror. Here we count the non-negative cosine index pairs. Fig. 2's labelled counts correspond to closed annuli. Section 2.1 describes open annuli. The half-integer endpoints in Fig. 3 give the same counts with either convention. Blömker, Sander & Wanner (2016)
k2_axis = (np.pi * np.arange(65)) ** 2
paper_k2 = jnp.asarray(k2_axis[:, None] + k2_axis[None, :])
narrow = [
int(spde.noise.Band(np.pi * (n - 0.5), np.pi * (n + 0.5))(paper_k2).sum())
for n in (11, 17, 23, 29)
]
wide = [
int(spde.noise.Band(np.pi * n, np.pi * (n + 10))(paper_k2).sum())
for n in (10, *range(15, 22))
]
assert narrow == [19, 29, 37, 44]
assert wide == [249, 327, 343, 361, 373, 387, 405, 419]
print(f"Fig. 3 mode counts {narrow}; Fig. 2 mode counts {wide}")
Fig. 3 mode counts [19, 29, 37, 44]; Fig. 2 mode counts [249, 327, 343, 361, 373, 387, 405, 419]
White and band forcing¶
Equation (2.1) places the paper's white noise directly in unnormalised
cosine products at \(\sigma=0.05\). Set SENSITIVITY=True to run the
doubled-amplitude comparison on the same key. The white and ring
observations follow Figs. 1 and 3.
white, white_times = simulate(WHITE_T, 4, spde.noise.Matern(0), WHITE_SIGMA, WHITE_SEED)
white_runs = [("white", white, white_times)]
if SENSITIVITY:
sensitive, sensitive_times = simulate(
WHITE_T, 4, spde.noise.Matern(0), WHITE_SENSITIVITY, WHITE_SEED
)
white_runs.append(("white sensitivity", sensitive, sensitive_times))
band, band_times = simulate(
BAND_T,
1,
spde.noise.Band(*(np.pi * np.asarray(RING) / EXTENT)),
BAND_SIGMA,
BAND_SEED,
)
for label, path, times in [*white_runs, ("band", band, band_times)]:
assert np.isfinite(path).all()
for field, time in zip(path, times, strict=True):
print(
f"{label} t={time:.9g}: peak={field.max():.6g} "
f"droplets={droplet_count(field)}"
)
white t=0.00265: peak=-0.461536 droplets=(0, 0.0) white t=0.0053: peak=0.982657 droplets=(3, 2.5) white t=0.00795: peak=1.0249 droplets=(6, 5.5) white t=0.0106: peak=1.02415 droplets=(16, 13.75) band t=0.005096: peak=1.06706 droplets=(48, 40.5)
Single-mode forcing and nodal domains¶
We count connected components of \(u>0\) using four-neighbour connectivity. The whole count uses the bounded field. The fractional count mirrors the field on both axes, joins the periodic seams and divides the periodic count by four. For \(\cos(j\pi x)\cos(k\pi y)\) it equals \(jk/2\). We compare at the first saved frame with \(\max u>0\) and again at the first with \(\max u\geq0.5\). The fixed discrepancy tolerance is the greater of half a component and 20% of the nodal count. Missing thresholds and counts outside that tolerance are reported. These diagnostics illustrate Observation 2.2 and Figs. 6–7. Observation 2.2 concerns small and medium frequencies. The (18,17) row is reported at both thresholds under the same rule. Blömker, Sander & Wanner (2016)
mode_results, mode_fields, mode_times = [], [], []
MODE_FRAMES = 48
for index, (j, k) in enumerate(MODES):
expected = j * k / 2
assert periodic_fraction(cosine_mode(M, j, k) > 0) == expected
path, times = simulate(
MODE_T, MODE_FRAMES, spde.noise.Modes([(j, k)]), MODE_SIGMA, MODE_SEED + index
)
assert np.isfinite(path).all()
peaks = path.max(axis=(1, 2))
for label, condition in (("positive", peaks > 0), ("half-height", peaks >= 0.5)):
hits = np.flatnonzero(condition)
if len(hits):
i = hits[0]
whole, fraction = droplet_count(path[i])
time = times[i]
status = (
"MATCH"
if abs(fraction - expected) <= max(0.5, 0.2 * expected)
else "MISMATCH"
)
else:
whole = fraction = time = None
status = "THRESHOLD NOT REACHED"
mode_results.append(((j, k), label, time, whole, fraction, expected, status))
print(
f"droplets mode={j, k} threshold={label} t={time} "
f"whole={whole} fractional={fraction} target={expected} {status}"
)
frame, time = path[-1], times[-1]
print(f"terminal mode={j, k} t={time:.9g}: droplets={droplet_count(frame)}")
mode_fields.append(frame.copy())
mode_times.append(time)
droplets mode=(10, 10) threshold=positive t=0.001062 whole=61 fractional=50.0 target=50.0 MATCH droplets mode=(10, 10) threshold=half-height t=0.001062 whole=61 fractional=50.0 target=50.0 MATCH terminal mode=(10, 10) t=0.025478: droplets=(61, 50.0)
droplets mode=(15, 15) threshold=positive t=0.004778 whole=128 fractional=112.5 target=112.5 MATCH droplets mode=(15, 15) threshold=half-height t=0.005307999999999999 whole=128 fractional=112.5 target=112.5 MATCH terminal mode=(15, 15) t=0.025478: droplets=(128, 112.5)
droplets mode=(18, 17) threshold=positive t=0.016454 whole=171 fractional=153.0 target=153.0 MATCH droplets mode=(18, 17) threshold=half-height t=0.016985999999999998 whole=171 fractional=153.0 target=153.0 MATCH terminal mode=(18, 17) t=0.025478: droplets=(171, 153.0)
Mass, Galerkin energy and conditional Itô budget¶
The constant coefficient is unforced. The Galerkin energy applies the same projection as the drift to the quartic term. Add the area divided by four to put the energy on the paper's double-well zero. The maximum mass error is printed.
For the budget, the deterministic substep gives \(a\) and a single independent Gaussian convolution gives a spatial variance \(s^2(x)\). Use the exact quartic correction \(6(Pa)^2s^2+3s^4\) and orthonormal Parseval for the quadratic terms. The left-point Itô rate combines \(-\|\nabla \delta E/\delta u\|^2\) with half the covariance-weighted Hessian trace. The residual divided by \(h\) tends to zero as the step shrinks. This is a one-state diagnostic derived from the numerical update.
trace_fields = np.concatenate((np.full((1, M, M), MU), white))
trace_times = np.r_[0, white_times]
trace_model = make_stepper(
M, H, spde.noise.Matern(0), WHITE_SIGMA, extent=EXTENT, noise_basis=NOISE_BASIS
)
mass = trace_fields.mean((1, 2))
energy = np.asarray(
jax.jit(jax.vmap(lambda u: spde.functionals.van_der_waals(trace_model, u[None])))(
jnp.asarray(trace_fields)
)
)
mass_error = np.max(abs(mass - MU))
assert mass_error <= 1e-12 and np.isfinite(energy).all()
print(f"trace max mass error={mass_error:.6g}; energy={energy.tolist()}")
budget_m, budget_mode, budget_sigma = 16, (1, 2), 0.2
mode_fn = cosine_mode(budget_m, *budget_mode)
u = MU + 0.2 * mode_fn
axis_k2 = (np.pi * np.arange(budget_m)) ** 2
k2 = axis_k2[:, None] + axis_k2[None, :]
basis_index = np.arange(budget_m)
mask = (basis_index[:, None] <= budget_m / 2 - 1) & (
basis_index[None, :] <= budget_m / 2 - 1
)
linear = k2 * (1 - EPSILON**2 * k2)
kinetic = EPSILON**2 * k2 - 1
u_coeff = fft.dctn(u, norm="ortho")
pu = fft.idctn(mask * u_coeff, norm="ortho")
chemical = kinetic * u_coeff + mask * fft.dctn(pu**3, norm="ortho")
dissipation = -np.sum(k2 * chemical**2) / budget_m**2
point_rate = budget_sigma**2 * mode_fn**2
trace_rate = 0.5 * kinetic[budget_mode] * point_rate.mean() + 1.5 * np.mean(
pu**2 * point_rate
)
def var_h(h, linear):
z = 2 * h * np.asarray(linear)
return h * np.divide(np.expm1(z), z, out=np.ones_like(z), where=z != 0)
budget_residuals = []
for h in (2e-4, 1e-4):
model = make_stepper(budget_m, h, spde.noise.Modes([budget_mode]), budget_sigma)
a = model.step_with_increment(
jnp.asarray(u_coeff)[None], jnp.zeros((1, budget_m, budget_m))
)
a = np.asarray(a)[0]
pa = fft.idctn(mask * a, norm="ortho")
s2 = var_h(h, linear[budget_mode]) * point_rate
extra = (
0.5 * kinetic[budget_mode] * s2.mean() + np.mean(6 * pa**2 * s2 + 3 * s2**2) / 4
)
energy_start = float(spde.functionals.van_der_waals(model, jnp.asarray(u)[None]))
energy_det = float(
spde.functionals.van_der_waals(model, model.to_physical(jnp.asarray(a)[None]))
)
residual = energy_det + extra - energy_start - h * (dissipation + trace_rate)
budget_residuals.append(residual / h)
print(
f"conditional budget h={h:.5g} residual={residual:.8g} "
f"residual/h={residual / h:.8g}"
)
assert abs(budget_residuals[1]) < abs(budget_residuals[0])
trace max mass error=1.11022e-16; energy=[-0.1437565975, -0.1436498611625417, -0.1442400549109861, -0.15053949445456374, -0.16314815613734202]
conditional budget h=0.0002 residual=-1.0837664e-07 residual/h=-0.00054188322 conditional budget h=0.0001 residual=-2.7046798e-08 residual/h=-0.00027046798
Linearised stochastic convolution¶
Section 4 of Blömker, Sander & Wanner (2016) gives an independent Brownian convolution for each mode. Set \(c_1=3\mu^2-1\) and \(c_3=0\), then the symbol is \(-\kappa(c_1+\varepsilon^2\kappa)\). The raw coefficient variance at time \(T\) is \(\sigma^2 T\varphi_1(2TL_k)\) in equation (4.3). We test an axis and two interior modes. For the interior mode \((1,2)\), the periodic even reflection and the bounded unnormalised draw give the same raw coefficient variance at the same \(\sigma\). We use independent keys and compare with the combined standard error.
law_m, law_t, law_sigma = 12, 0.025, 0.25
law_modes = np.array([(0, 2), (1, 2), (2, 3)])
i, j = law_modes.T
k2 = np.pi**2 * np.sum(law_modes**2, axis=1)
c1 = 3 * MU**2 - 1
symbols = -k2 * (c1 + EPSILON**2 * k2)
expected_power = law_sigma**2 * var_h(law_t, symbols)
law_model = make_stepper(
law_m, law_t, spde.noise.Modes(law_modes.tolist()), law_sigma, c1=c1, c3=0
)
norm = law_m / np.sqrt(np.where(i == 0, 1, 2) * np.where(j == 0, 1, 2))
reflected = spde.StochasticCahnHilliard(
2,
2.0,
2 * law_m,
law_t,
diffusivity=1.0,
gamma=EPSILON**2,
first_order_coefficient=c1,
third_order_coefficient=0.0,
sigma=law_sigma,
noise_spectrum=spde.noise.Modes([(1, 2)]),
noise_symmetry="even",
)
@jax.jit
def law_chunk(key, key_reflected):
a = jax.vmap(law_model.sample_increment)(jax.random.split(key, 64))
b = jax.vmap(reflected.sample_increment)(jax.random.split(key_reflected, 64))
bounded_power = (a[:, 0, i, j] / norm) ** 2
reflected_power = (4 * b[:, 0, 1, 2].real / (2 * law_m) ** 2) ** 2
return jnp.column_stack((bounded_power, reflected_power))
power = np.concatenate(
[
np.asarray(law_chunk(a, b))
for a, b in zip(
jax.random.split(jax.random.key(329120), 50),
jax.random.split(jax.random.key(329121), 50),
strict=True,
)
]
)
targets = np.r_[expected_power, expected_power[1]]
powers = power.mean(0)
se = power.std(0, ddof=1) / np.sqrt(len(power))
z = abs(powers - targets) / se
for label, measured, err, target, distance in zip(
[*law_modes.tolist(), "reflected (1,2)"], powers, se, targets, z, strict=True
):
print(
f"linear mode={label} power={measured:.8g} SE={err:.6g} "
f"target={target:.8g} error_SE={distance:.5g}"
)
cross = abs(powers[1] - powers[-1]) / np.hypot(se[1], se[-1])
print(f"bounded/reflected single-mode agreement={cross:.6g} combined SE")
assert max(z) <= 5 and max(se / powers) <= 0.04 and cross <= 5
linear mode=[0, 2] power=0.0014827207 SE=3.72945e-05 target=0.0014946971 error_SE=0.32113 linear mode=[1, 2] power=0.0015311168 SE=3.7788e-05 target=0.0014779235 error_SE=1.4077 linear mode=[2, 3] power=0.0013447776 SE=3.33058e-05 target=0.0013468492 error_SE=0.062199 linear mode=reflected (1,2) power=0.001460971 SE=3.60709e-05 target=0.0014779235 error_SE=0.46998 bounded/reflected single-mode agreement=1.34275 combined SE
Figures¶
The white-noise panel uses four saved times at the stated amplitude.
The optional sensitivity row shows the doubled-amplitude case.
The single-mode panels show the final observation from Fig. 6.
Dashed lines mark the cosine nodes. The
paired band and energy panels use the same saved trajectories
reported above. Set SAVE_FIGURES=True to write the figures.
def field_row(fields, labels, title, filename, nodal=None):
fig, axes = plt.subplots(
1,
len(fields),
squeeze=False,
figsize=(3.1 * len(fields) + 0.5, 3.5),
layout="constrained",
)
for index, (ax, field, label) in enumerate(
zip(axes[0], fields, labels, strict=True)
):
image = ax.imshow(
field.T,
origin="lower",
extent=(0, EXTENT, 0, EXTENT),
cmap="RdBu_r",
vmin=-1,
vmax=1,
)
ax.set(xlabel="x", ylabel="y", title=label)
if nodal is not None:
j, k = nodal[index]
for value in EXTENT * (np.arange(j) + 0.5) / j:
ax.axvline(value, color="0.82", linestyle="--", linewidth=0.35)
for value in EXTENT * (np.arange(k) + 0.5) / k:
ax.axhline(value, color="0.82", linestyle="--", linewidth=0.35)
fig.colorbar(image, ax=list(axes[0]), label="concentration")
fig.suptitle(title)
return fig, filename
config = f"L={EXTENT:g}, M={M}, ε={EPSILON:g}, μ={MU:g}".replace("-", "−")
white_labels = [f"t={t:.4g}" for t in white_times]
figures = [
field_row(white, white_labels, f"White noise σ={WHITE_SIGMA:g}, {config}", "white"),
field_row(
mode_fields,
[f"{m}, t={t:.4g}" for m, t in zip(MODES, mode_times, strict=True)],
f"Single modes σ={MODE_SIGMA:g}, {config}",
"single_modes",
MODES,
),
]
if SENSITIVITY:
figures.insert(
1,
field_row(
sensitive,
white_labels,
f"White sensitivity σ={WHITE_SENSITIVITY:g}, {config}",
"white_sensitivity",
),
)
fig, (band_ax, energy_ax) = plt.subplots(1, 2, figsize=(8, 3.5), layout="constrained")
image = band_ax.imshow(
band[-1].T,
origin="lower",
extent=(0, EXTENT, 0, EXTENT),
cmap="RdBu_r",
vmin=-1,
vmax=1,
)
band_ax.set(
xlabel="x",
ylabel="y",
title=f"Band {RING}, σ={BAND_SIGMA:g}, t={band_times[-1]:.4g}",
)
fig.colorbar(image, ax=band_ax, label="concentration")
energy_ax.plot(trace_times, energy + EXTENT**2 / 4, "o-")
energy_ax.set(
xlabel="time", ylabel="Galerkin energy", title=f"White noise σ={WHITE_SIGMA:g}"
)
fig.suptitle(config)
figures.append((fig, "band_and_energy"))
if SAVE_FIGURES:
OUTPUT.mkdir(exist_ok=True)
for fig, name in figures:
fig.savefig(OUTPUT / f"{name}.png", dpi=140)
if SHOW_FIGURES:
plt.show()
else:
for fig, _ in figures:
plt.close(fig)