Shallow water in 1-D#
The smallest complete Zoomy run: derive a model, freeze it, pick a scheme, solve, plot. About twenty lines of actual work.
Shallow water is not typed out by hand here — it is the level-0 member of the
Shallow Moment family, SME(level=0). Everything on this page is symbolic until
the last step.
See Model for the authoring surface this uses.
1. The model#
Three ingredients: the family, the physics closures, and the run conditions (boundary + initial). Nothing here is numerical yet — no mesh, no timestep.
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, # level 0 == shallow water
closures=[Newtonian(), NavierSlip(), StressFree()],
boundary_conditions=BC.BoundaryConditions([
BC.Wall(tag="left"), # closed box: nothing enters or leaves
BC.Wall(tag="right"),
]),
initial_conditions=IC.RP( # dam break: h = 2 on the left, 1 on the right
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 it into operators#
SystemModel.from_model walks the model once and freezes the operator matrices.
Print it before running anything — the operator slots are the cheapest bug
detector in the framework. An empty hydrostatic_pressure on a free-surface
model, or an empty non-conservative matrix, is visible here in seconds.
from zoomy_core.systemmodel import SystemModel
sm = SystemModel.from_model(model)
# Display, do NOT print: describe() has a _repr_markdown_ that renders the
# operator matrices as real LaTeX. print() would dump the raw markup.
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
Note sm.aux_state: the spatial derivatives (dhdx, dq0dx, dbdx) were
discovered and registered automatically. You never write a finite-difference
stencil — the solver fills them in one least-squares gradient pass per step.
print("state ", [str(s) for s in sm.state])
print("aux state", [str(s) for s in sm.aux_state])
state ['b', 'h', 'q_0']
aux state ['dq0dx', 'dhdx', 'dbdx']
3. Add the numerics#
NumericalSystemModel is the SystemModel plus the scheme choices. Defaults are
sensible (PositiveNonconservativeRusanov, first order); we spell out the
reconstruction to show where that knob lives.
from zoomy_core.numerics import NumericalSystemModel, ReconstructionSpec
nsm = NumericalSystemModel.from_system_model(
sm, reconstruction=ReconstructionSpec(order=1))
4. Solve#
A 50-cell mesh on x in [0, 10], adaptive timestep at CFL 0.9, to t = 0.5.
SymbolicHyperbolicSolverNumpy is the reference solver: pure Python and NumPy, no
compiler. setup writes one time step as a sympy graph (the solver template),
prints it as Python and returns the initial state (Q, Qaux); run marches it.
The JAX, OpenFOAM and AMReX solvers print the same template in their own language.
from zoomy_core.mesh import LSQMesh
from zoomy_core.symsolver.numpy_backend import SymbolicHyperbolicSolverNumpy
mesh = LSQMesh.create_1d(domain=(0.0, 10.0), n_inner_cells=50)
solver = SymbolicHyperbolicSolverNumpy(time_end=0.5, cfl=0.9)
Q, Qaux = solver.setup(mesh, nsm)
time, Q, Qaux = solver.run(Q, Qaux)
b, h, q = Q
print(f"t = {time} h in [{h.min():.6f}, {h.max():.6f}]")
t = 0.5 h in [1.000000, 2.000000]
The box is closed, so the mass must not change: 25 cells at h = 2 and 25 at
h = 1 give sum h = 75.
print(f"sum h = {h.sum():.12f}")
assert abs(h.sum() - 75.0) < 1e-9, "wall boundaries are leaking mass"
sum h = 75.000000000000
The template the solver just ran, as Python (the first lines of the time loop):
print("\n".join(solver.source.splitlines()[:12]))
def hyperbolic(Q, Qaux, p, time, time_end, mesh, tok):
def f1(time_2, Q_2, Qaux_2, n_write, n_checkpoint, tok_2):
return (time_2 < time_end)
x2 = face_inradius(mesh)
def f3(time_3, Q_3, Qaux_3, n_write_2, n_checkpoint_2, tok_3):
W = pointwise(nsm.reconstruction_variables, Q_3, Qaux_3, p)
x4 = take(Q_3, (1, ))
W_2 = put(W, (0, ), x4)
WL, WR = cell_traces(W_2, mesh)
x8 = take(WL, (0, ))
x9 = take(WL, (1, ))
WL_2 = put(WL, (0, ), -x8 + x9)
5. Plot#
zoomy_plotting is the house style — a case never hand-rolls its own styling.
import matplotlib.pyplot as plt
import zoomy_plotting as zp
x = mesh.cell_centers[0, :mesh.n_inner_cells]
order = np.argsort(x)
with zp.apply_style():
fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(9.0, 3.2))
zp.line_plot(ax0, [
{"x": x[order], "y": (b + h)[order], "label": "surface b + h", "role": "water"},
], xlabel="x", ylabel="elevation", title=f"free surface at t = {time}")
zp.line_plot(ax1, [
{"x": x[order], "y": q[order], "label": "discharge q", "role": "reference"},
], xlabel="x", ylabel="q", title="discharge")
for ax in (ax0, ax1):
ax.legend()
fig.tight_layout()