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:

\[M(Q)\,\partial_t Q + \nabla\cdot\!\big(F(Q) + P(Q)\big) + \sum_{d} B_{d}(Q)\,\partial_{d} Q - \nabla\cdot\!\big(A(Q)\,\nabla Q\big) - S(Q) = 0\]

State \(Q\):

\[\begin{split} \left[\begin{matrix}b\\h\\q_{0}\end{matrix}\right] \end{split}\]

Auxiliary \(Q_{aux}\):

\[\begin{split} \left[\begin{matrix}dq0dx\\dhdx\\dbdx\end{matrix}\right] \end{split}\]

Mass matrix \(M\):

\[\begin{split} \left[\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 1\end{matrix}\right] \end{split}\]

Flux \(F\):

\[\begin{split} \left[\begin{matrix}0\\q_{0}\\\frac{q_{0}^{2}}{h}\end{matrix}\right] \end{split}\]

Hydrostatic pressure \(P\):

\[\begin{split} \left[\begin{matrix}0\\0\\\frac{g h^{2}}{2}\end{matrix}\right] \end{split}\]

Diffusive flux \(A\) \(= 0\)

NCP \(B\):

\[\begin{split} \left[\begin{matrix}0 & 0 & 0\\0 & 0 & 0\\g h & 0 & 0\end{matrix}\right] \end{split}\]

Source \(S\) (implicit):

\[\begin{split} \left[\begin{matrix}0\\0\\e_{x} g h - \frac{\lambda_{s} q_{0}}{h \rho}\end{matrix}\right] \end{split}\]

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={})

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()
../../../_images/af3d0c44320a30c8c4fd7314f19f6c6356e6a382a141fb4cd136b00c2ea47928.png

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.