A sound pulse in a two-layer room: spectral elements on hexahedra
spectral spectral_wave_layers_3d.py
A short pulse of sound starts at a point in a closed room with rigid walls. Sound is twice as fast in the upper half of the room. The sphere of sound reaches the interface, part of it crosses into the fast layer as a wider dome, part is reflected, and all of it bounces between the walls.

The surfaces \(u=\pm0.04\) of the computed pressure (orange positive, blue negative) behind the plane \(y=\tfrac12\); the pale plane is the interface.
The problem
so \(c=1\) below and \(c=2\) above. The pulse is a Mexican hat of width \(\sigma=0.08\), released at rest. A point pulse in a uniform medium is a free spherical wave: \(r\,u\) solves the 1-D wave equation, so
The jNO code
\(8^3\) hexahedra with Q5 elements on the Gauss–Lobatto–Legendre points. quadrature="gll" integrates at the nodes, so
the mass matrix is diagonal and an explicit scheme needs no linear solve; matrix_free=True applies the stiffness
cell by cell with sum factorisation and never stores it. The rigid walls need no term:
def march(n, order, T, steps, c2, u0, ts):
"""Explicit march of u_tt = div(c2 grad u) on n^3 Q_order hexahedra; the state [u, u_t] at the times ts."""
d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=n).quad().domain(time=(0.0, T, steps))
x, y, z, t = d.variable("interior", split=True)
ci = d.variable("initial", split=True)
u = d.unknown(order=order)
v = u.test()
ui, vi = u.bind(x=x, y=y, z=z, t=t), v.bind(x=x, y=y, z=z, t=t)
c2 = c2(z) if callable(c2) else c2
fem = jno.fem(
[
ui.tt * vi + c2 * (ui.x * vi.x + ui.y * vi.y + ui.z * vi.z), # int u_tt phi + c^2 grad u . grad phi = 0
u(*ci) - u0(*ci[:3]), # the pulse ...
u.bind(x=ci[0], y=ci[1], z=ci[2], t=ci[3]).t - 0.0, # ... at rest
],
quadrature="gll", # diagonal mass
matrix_free=True, # the stiffness is applied, never stored
)
Y = np.asarray(fem.solve(time=jno.solve.erk("rk4"), save_ts=ts).fn())
return np.asarray(fem.points)[:, :3], Y[:, : fem.offsets[1]], Y[:, fem.offsets[1] :]
The layered medium is the coefficient, an expression of \(z\):
layers = lambda z: 1 + 1.5 * (1 + jno.np.tanh((z - 0.5) / 0.02)) # c^2: 1 below z = 1/2, 4 above, over ~0.04
Result
A standing wave \(\cos\pi x\cos\pi y\cos\pi z\,\cos(\sqrt3\,\pi t)\) on \(2^3\) cells, error at \(t=0.3\):
| degree | Q4 | Q6 | Q8 |
|---|---|---|---|
| max error | \(2.3\times10^{-5}\) | \(1.1\times10^{-7}\) | \(4.3\times10^{-11}\) |
The point pulse against d'Alembert at \(t=0.08\), on the \(8^3\) mesh of the layered run:
| degree | Q4 | Q5 | Q6 |
|---|---|---|---|
| max error relative to the peak | \(5.6\times10^{-3}\) | \(6.5\times10^{-4}\) | \(1.6\times10^{-4}\) |
The layered room (68 921 unknowns, 1 200 steps): the discrete energy \(E=\tfrac12\,\dot u^{\!\top}M\dot u+\tfrac12\,u^{\top}K u\) drifts by \(1.2\times10^{-8}\).
Full script
The whole script, as it runs in the tests
"""A sound pulse in a two-layer room: Q5 spectral elements on hexahedra, marched explicitly.
The scalar wave equation u_tt = div(c^2 grad u) in the unit cube with rigid walls (the natural condition,
du/dn = 0). A Mexican-hat pulse (a positive core in a negative shell) starts at rest in the lower layer, where
c = 1; above z = 1/2 the sound is twice as fast. The pulse spreads as a sphere, part of it reflects at the
interface and part is refracted into the fast layer, where the wavefront runs ahead of the sphere that made it.
Q5 elements on 8 x 8 x 8 hexahedra: the Gauss-Lobatto-Legendre rule at the nodes makes the mass matrix
diagonal, so the fourth-order Runge-Kutta march needs one stiffness application per stage and solves nothing,
and ``matrix_free=True`` never stores the stiffness.
"""
import jax
import numpy as np
import jno
jax.config.update("jax_enable_x64", True)
run = jno.setup(__file__)
SIGMA, SRC, N, ORDER = 0.08, (0.5, 0.5, 0.36), 8, 5 # pulse width and place, cells per side, degree
def march(n, order, T, steps, c2, u0, ts):
"""Explicit march of u_tt = div(c2 grad u) on n^3 Q_order hexahedra; the state [u, u_t] at the times ts."""
d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=n).quad().domain(time=(0.0, T, steps))
x, y, z, t = d.variable("interior", split=True)
ci = d.variable("initial", split=True)
u = d.unknown(order=order)
v = u.test()
ui, vi = u.bind(x=x, y=y, z=z, t=t), v.bind(x=x, y=y, z=z, t=t)
c2 = c2(z) if callable(c2) else c2
fem = jno.fem(
[
ui.tt * vi + c2 * (ui.x * vi.x + ui.y * vi.y + ui.z * vi.z), # int u_tt phi + c^2 grad u . grad phi = 0
u(*ci) - u0(*ci[:3]), # the pulse ...
u.bind(x=ci[0], y=ci[1], z=ci[2], t=ci[3]).t - 0.0, # ... at rest
],
quadrature="gll", # diagonal mass
matrix_free=True, # the stiffness is applied, never stored
)
Y = np.asarray(fem.solve(time=jno.solve.erk("rk4"), save_ts=ts).fn())
return np.asarray(fem.points)[:, :3], Y[:, : fem.offsets[1]], Y[:, fem.offsets[1] :]
ricker = lambda s2: (1 - s2 / SIGMA**2) * jno.np.exp(-s2 / (2 * SIGMA**2)) # the Mexican hat in s2 = s^2
pulse = lambda s: lambda x, y, z: ricker((x - s[0]) ** 2 + (y - s[1]) ** 2 + (z - s[2]) ** 2)
layers = lambda z: 1 + 1.5 * (1 + jno.np.tanh((z - 0.5) / 0.02)) # c^2: 1 below z = 1/2, 4 above, over ~0.04
# 1. Standing wave of the rigid box, cos(pi x) cos(pi y) cos(pi z) cos(sqrt(3) pi t): error against the degree
mode = lambda x, y, z: jno.np.cos(np.pi * x) * jno.np.cos(np.pi * y) * jno.np.cos(np.pi * z)
for order in (4, 6, 8):
P, U, _ = march(2, order, 0.3, 301, 1.0, mode, np.array([0.3]))
exact = np.prod(np.cos(np.pi * P), axis=1) * np.cos(np.sqrt(3) * np.pi * 0.3)
print(f"standing wave, 2^3 cells, Q{order}: max error {abs(U[-1] - exact).max():.1e}")
assert abs(U[-1] - exact).max() < 1e-9 # Q8
# 2. The point-like pulse in a uniform medium against the spherical wave, before it reaches a wall
T0, C0 = 0.08, (0.45, 0.5, 0.55)
for order in (4, 5, 6):
P, U, _ = march(N, order, T0, 201, 1.0, pulse(C0), np.array([T0]))
r, h = np.linalg.norm(P - C0, axis=1), lambda s: (1 - s**2 / SIGMA**2) * np.exp(-(s**2) / (2 * SIGMA**2))
exact = ((r - T0) * h(r - T0) + (r + T0) * h(r + T0)) / (2 * r) # d'Alembert for r u in three dimensions
err = abs(U[-1] - exact).max() / abs(exact).max()
print(f"spherical pulse at t = {T0}, {N}^3 cells, Q{order}: max error {err:.1e} of the peak {abs(exact).max():.2f}")
assert err < 1e-3 # Q6
# 3. The two layers, 0.6 time units: energy of the explicit march
T, STEPS = 0.6, 1201
ts = np.linspace(0, T, 61)
P, U, V = march(N, ORDER, T, STEPS, layers, pulse(SRC), ts)
d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=N).quad().domain()
x, y, z = d.variable("interior", split=True)[:3]
u = d.unknown(order=ORDER)
ui, vi = u.bind(x=x, y=y, z=z), u.test().bind(x=x, y=y, z=z)
stiffness = jno.fem([layers(z) * (ui.x * vi.x + ui.y * vi.y + ui.z * vi.z)], quadrature="gll", matrix_free=True)
mass = jno.fem([ui * vi], quadrature="gll", matrix_free=True)
(K, _), (M, _) = stiffness.operator, mass.operator
w = np.asarray(M.diag())
E = np.array([0.5 * (w * V[i] ** 2).sum() + 0.5 * U[i] @ np.asarray(K @ U[i]) for i in range(len(ts))])
drift = abs(E / E[0] - 1).max()
print(
f"two layers: {len(P)} DOFs, energy drift over {STEPS - 1} steps {drift:.1e}, peak |u| at the end {abs(U[-1]).max():.3f}"
)
assert drift < 1e-6