AMReX: from symbolic model to generated C++#
AMReX is Zoomy’s block-structured adaptive-mesh backend. The model you write is the same one the NumPy tutorial uses — only the final step differs: instead of running the solver template in NumPy, it is printed as C++ and compiled against AMReX.
Before you start — you need the AMReX container#
This page does not stop at the generated code: it compiles it and runs the
case. The notebook itself runs on your machine, with zoomy_core and
zoomy_amrex installed from a clone of the repository; the driver builds and
runs the C++ inside the AMReX Apptainer image, so you need apptainer and the
image, but no local AMReX:
git clone https://github.com/ZoomyLab/Zoomy.git && cd Zoomy
git submodule update --init library/zoomy_amrex
pip install -e library/zoomy_core -e library/zoomy_amrex -e library/zoomy_plotting jupyterlab
apptainer pull containers/zoomy_amrex/zoomy_amrex.sif oras://ghcr.io/zoomylab/zoomy_amrex_sif:latest
The driver looks for the image in containers/zoomy_amrex/ of the clone, or in
the directory ZOOMY_AMREX_CONTAINERS. See Installation
for all containers and Backends for the AMReX settings.
1. The model#
Identical to the NumPy tutorial — that is the point. Shallow water as
SME(level=0), wall boundaries, dam-break initial state. Nothing here is
AMReX’s: the driver reads the sides of its Cartesian grid off the mesh and their
boundary conditions off the model.
import numpy as np
from zoomy_core.model.models import SME, Newtonian, NavierSlip, StressFree
import zoomy_core.model.boundary_conditions as BC
import zoomy_core.model.initial_conditions as IC
model = SME(
level=0,
closures=[Newtonian(), NavierSlip(), StressFree()],
boundary_conditions=BC.BoundaryConditions([
BC.Wall(tag="left"), BC.Wall(tag="right"),
]),
initial_conditions=IC.RP(
high=lambda n: np.array([0.0, 2.0] + [0.0] * (n - 2)),
low=lambda n: np.array([0.0, 1.0] + [0.0] * (n - 2)),
jump_position_x=5.0,
),
)
2. Freeze and inspect#
describe() is the cheapest sanity check there is. Read the slots before you
spend a compile cycle: an empty hydrostatic_pressure row on a free-surface
model means the derivation went wrong, and you can see that here in seconds
rather than after a build.
from zoomy_core.systemmodel import SystemModel
sm = SystemModel.from_model(model)
sm.describe()
SystemModel — 3 equations, 1 spatial dimension
Parameters: \(g = 9.81\), \(\rho = 1.0\), \(\nu = 0.0\), \(\lambda_{s} = 0.0\), \(e_{x} = 0.0\)
System form:
State \(Q\):
Auxiliary \(Q_{aux}\):
Mass matrix \(M\):
Flux \(F\):
Hydrostatic pressure \(P\):
Diffusive flux \(A\) \(= 0\)
NCP \(B\):
Source \(S\) (implicit):
Operations: from_model, declare_roles, declare_tags, declare_roles, declare_tags
3. Attach the numerics#
Same NumericalSystemModel as every other backend. The scheme lives here, at
the symbolic level — not in the AMReX code. That is deliberate: every
backend gets the same well-balancing, positivity and tolerances, emitted from
one place, so they cannot drift apart.
from zoomy_core.numerics import NumericalSystemModel, ReconstructionSpec
nsm = NumericalSystemModel.from_system_model(
sm, reconstruction=ReconstructionSpec(order=1))
riemann = nsm.riemann
print("Riemann solver :", getattr(riemann, "__name__", None) or type(riemann).__name__)
print("reconstruction :", nsm.reconstruction)
Riemann solver : PositiveNonconservativeRusanov
reconstruction : ReconstructionSpec(order=1, limiter=Limiter.venkatakrishnan, free_surface_aware=False, positivity='', variables=ReconstructedVariables.model, bed=BedReconstruction.derived, limiters={}, ties={})
4. Print and build the C++#
SymbolicHyperbolicSolverAmrex takes the same settings as the NumPy solver.
Its run(mesh, nsm, Q0, workdir) prints the solver template as C++, builds it
in the container and runs it. The build writes two headers: Solver.H, the time
step (the same template every backend prints), and Kernels.H, the model’s
operators and the scheme’s numerical flux, both straight off the
NumericalSystemModel. The binary is cached by a hash of the sources; with
build_only=True, run stops there and returns it.
The first build compiles AMReX itself, so expect a minute or two; later builds
of the same case are instant. The build tree and the binaries go to
library/zoomy_amrex/.symcache (or ZOOMY_AMREX_SYMCACHE), about 500 MB.
from zoomy_core.mesh import LSQMesh
from zoomy_amrex.symsolver import SymbolicHyperbolicSolverAmrex
mesh = LSQMesh.create_1d(domain=(0.0, 10.0), n_inner_cells=100)
n = mesh.n_inner_cells
Q0 = sm.initial_conditions.apply(mesh.cell_centers[:, :n], np.zeros((len(sm.state), n)))
settings = dict(time_end=0.5, cfl=0.9, dt_write=0.125)
binary = SymbolicHyperbolicSolverAmrex(build_only=True, **settings).run(
mesh, nsm, Q0, "dambreak_amrex")
solver_h = (binary.parent / "Solver.H").read_text()
kernels_h = (binary.parent / "Kernels.H").read_text()
print(f"Solver.H: {len(solver_h.splitlines())} lines, Kernels.H: {len(kernels_h.splitlines())} lines")
Solver.H: 89 lines, Kernels.H: 171 lines
The head of Solver.H: one time step as C++ — reconstruct the face states,
apply the boundary conditions, solve a Riemann problem on every face, choose the
step from the wave speeds.
print("\n".join(solver_h.splitlines()[:32]))
inline auto run = [](auto Q, auto Qaux, auto p, auto time, auto time_end, auto mesh, auto tok) {
auto f1 = [&](auto time_2, auto Q_2, auto Qaux_2, auto n_write, auto n_checkpoint, auto tok_2) {
return time_2 < time_end;
};
auto x2 = face_inradius(mesh);
auto f3 = [&](auto time_3, auto Q_3, auto Qaux_3, auto n_write_2, auto n_checkpoint_2, auto tok_3) {
auto W = pointwise(nsm.reconstruction_variables, Q_3, Qaux_3, p);
auto x4 = take(Q_3, std::make_tuple(1));
auto W_2 = put(W, std::make_tuple(0), x4);
auto x5 = cell_traces(W_2, mesh);
auto WL = std::get<0>(x5);
auto WR = std::get<1>(x5);
auto x6 = take(WL, std::make_tuple(0));
auto x7 = take(WL, std::make_tuple(1));
auto WL_2 = put(WL, std::make_tuple(0), -x6 + x7);
auto x8 = face_aux(Qaux_3, mesh);
auto AL = std::get<0>(x8);
auto AR = std::get<1>(x8);
auto QL = pointwise(nsm.state_from_reconstruction, WL_2, AL, p);
auto x9 = take(WR, std::make_tuple(0));
auto x10 = take(WR, std::make_tuple(1));
auto WR_2 = put(WR, std::make_tuple(0), -x9 + x10);
auto QR = pointwise(nsm.state_from_reconstruction, WR_2, AR, p);
auto QR_2 = boundary_traces(nsm.boundary_conditions, Q_3, QL, QR, Qaux_3, p, time_3, mesh);
auto x11 = faces<3>(nsm.numerical_face_sides_speed, QL, QR_2, AL, AR, p, mesh);
auto Wm = std::get<0>(x11);
auto Wp = std::get<1>(x11);
auto S = std::get<2>(x11);
auto dt = reduce_min(1.8*x2*(1.0/(S)));
auto x12 = minimum(dt, 5.0);
auto x13 = -time_3;
auto x14 = 0.125*n_write_2;
Where the physics ended up#
Kernels.H holds one functor per operator. The source, for example, with the
parameters p = (g, rho, nu, lambda_s, e_x) and Qaux(3) = 1/h: on the momentum
row the gravity along a sloped bed, g e_x h, and the NavierSlip bed friction,
-lambda_s u / rho (both zero here: e_x = lambda_s = 0).
lines = kernels_h.splitlines()
start = next(i for i, l in enumerate(lines) if "struct source_k" in l)
print("\n".join(lines[start:start + 13]))
struct source_k
{
static constexpr int family = 4, n_out = 3, n_in = 3, n_aux = 4, n_nrm = 1;
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::SmallMatrix<amrex::Real, 3, 1> operator()(amrex::SmallMatrix<amrex::Real, 3, 1> const& Q, amrex::SmallMatrix<amrex::Real, 4, 1> const& Qaux, amrex::SmallMatrix<amrex::Real, 5, 1> const& p, amrex::Real time, amrex::Real dt, amrex::SmallMatrix<amrex::Real, 3, 1> const& X) const noexcept
{
amrex::SmallMatrix<amrex::Real,3,1> res;
res(0, 0) = 0;
res(1, 0) = 0;
res(2, 0) = p(4, 0)*p(0, 0)*Q(1, 0) - Qaux(3, 0)*p(3, 0)*Q(2, 0)/p(1, 0);
return res;
}
};
static constexpr source_k source{};
5. Running it#
The same settings without build_only: the run finds the cached binary, writes
the case (grid, initial state, inputs) into dambreak_amrex/, runs it in the
container and reads the result back. Q is the final state in the mesh’s cell
order; with dt_write the driver keeps the snapshots in solver.snapshots, a
list of (time, Q).
solver = SymbolicHyperbolicSolverAmrex(**settings)
time, Q = solver.run(mesh, nsm, Q0, "dambreak_amrex")
times = [t for t, _ in solver.snapshots]
print(f"t = {time}, {solver.steps} steps, {len(times)} snapshots at t =", times)
t = 0.5, 32 steps, 5 snapshots at t = [0.0, 0.125, 0.25, 0.375, 0.5]
The box is closed, so mass must be conserved: 100 cells over x in [0, 10],
half at h = 2 and half at h = 1, gives 150.
for t, Qs in solver.snapshots:
print(f"t = {t:.3f} sum h = {Qs[1].sum():.10f} "
f"h in [{Qs[1].min():.4f}, {Qs[1].max():.4f}] "
f"max |q_0| = {np.abs(Qs[2]).max():.4f}")
drift = max(abs(Qs[1].sum() - 150.0) for _, Qs in solver.snapshots)
print(f"\nworst mass drift = {drift:.3e}")
assert drift < 1e-9, "wall boundaries are leaking mass"
t = 0.000 sum h = 150.0000000000 h in [1.0000, 2.0000] max |q_0| = 0.0000
t = 0.125 sum h = 150.0000000000 h in [1.0000, 2.0000] max |q_0| = 1.8515
t = 0.250 sum h = 150.0000000000 h in [1.0000, 2.0000] max |q_0| = 1.8838
t = 0.375 sum h = 150.0000000000 h in [1.0000, 2.0000] max |q_0| = 1.8890
t = 0.500 sum h = 150.0000000000 h in [1.0000, 2.0000] max |q_0| = 1.8914
worst mass drift = 2.842e-14
6. Plot#
import matplotlib.pyplot as plt
import zoomy_plotting as zp
x = mesh.cell_centers[0, :n]
order = np.argsort(x)
with zp.apply_style():
fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(9.5, 3.6))
shades = np.linspace(0.75, 0.0, len(solver.snapshots))
for (t, Qs), g in zip(solver.snapshots, shades):
b, h, q = Qs[0][order], Qs[1][order], Qs[2][order]
ax0.plot(x[order], b + h, lw=1.8, color=str(g), label=f"t = {t:.2f}")
ax1.plot(x[order], q, lw=1.8, color=str(g), label=f"t = {t:.2f}")
ax0.set(xlabel="x", ylabel="elevation", title="free surface")
ax1.set(xlabel="x", ylabel="q_0", title="discharge")
for ax, tag in ((ax0, "(a)"), (ax1, "(b)")):
ax.text(0.02, 0.95, tag, transform=ax.transAxes, va="top")
ax.legend()
fig.tight_layout()
Going further#
One case, one level, no refinement. The same driver takes ranks=N for MPI,
gpu=True for the CUDA image and amr=dict(max_level=..., ...) for adaptive
refinement, see AMReX: adaptive mesh refinement and
Backends. The maintained end-to-end runs are the
cross-backend test matrix, which runs every case on
JAX, OpenFOAM and AMReX and holds them to the same checks.
What carries over#
Nothing about the model changed to target AMReX. Swap the last step and the same
nsm drives NumPy, JAX, or OpenFOAM — see
Solvers and options.