OpenFOAM: the same model, printed as C++

OpenFOAM: the same model, printed as C++#

Goal: Run the 1-D dam break of the NumPy tutorial on OpenFOAM and compare it with the NumPy solver.

Prerequisite: AMReX: from symbolic model to generated C++

The notebook runs where zoomy_core and zoomy_foam are installed. The driver builds and runs the C++ in the OpenFOAM container, so apptainer and the image are needed.

1. The NumericalSystemModel#

Shallow water, wall boundaries, second order. Nothing here is OpenFOAM’s.

import numpy as np

import zoomy_core.model.boundary_conditions as BC
import zoomy_core.model.initial_conditions as IC
from zoomy_core.mesh import LSQMesh
from zoomy_core.model.models import SME
from zoomy_core.model.models.closures import ManningFriction, Newtonian, StressFree
from zoomy_core.numerics import Limiter, NumericalSystemModel, ReconstructionSpec
from zoomy_core.systemmodel import SystemModel

model = SME(
    level=0, dimension=2,
    closures=[Newtonian(), ManningFriction(), StressFree()],
    boundary_conditions=BC.BoundaryConditions(
        [BC.Extrapolation(tag="left"), BC.Extrapolation(tag="right")]),
)
sm = SystemModel.from_model(model)
sm.initial_conditions = IC.UserFunction(
    function=lambda x: np.array([0.0, 2.0 if x[0] < 5.0 else 1.0, 0.0]))
nsm = NumericalSystemModel.from_system_model(
    sm, reconstruction=ReconstructionSpec(order=2, limiter=Limiter.minmod))
mesh = LSQMesh.create_1d(domain=(0.0, 10.0), n_inner_cells=300)
n = mesh.n_inner_cells
Q0 = sm.initial_conditions.apply(np.asarray(mesh.cell_centers)[:, :n], np.zeros((3, n)))

2. OpenFOAM#

run(mesh, nsm, Q0, workdir) prints the solver template as C++, builds it in the container (cached by a hash of the sources) and runs it. nprocs=N runs on N MPI ranks.

import tempfile
from pathlib import Path

from zoomy_foam.symsolver import SymbolicHyperbolicSolverFoam

foam = SymbolicHyperbolicSolverFoam(time_end=0.5, cfl=0.9)
time, Q = foam.run(mesh, nsm, Q0, Path(tempfile.mkdtemp()) / "dambreak_foam")

h = np.asarray(Q)[1]
print(f"t = {time:.3f}, cells = {h.size}, h in [{h.min():.5f}, {h.max():.5f}]")
t = 0.500, cells = 300, h in [1.00000, 2.00000]

3. Compare with NumPy#

from zoomy_core.symsolver.numpy_backend import SymbolicHyperbolicSolverNumpy

reference = SymbolicHyperbolicSolverNumpy(time_end=0.5, cfl=0.9)
Qn, Qauxn = reference.setup(mesh, nsm)
_, Qn, _ = reference.run(Qn, Qauxn)

print(f"max |h_foam - h_numpy| = {np.abs(h - Qn[1]).max():.2e}")
max |h_foam - h_numpy| = 2.16e-09
assert np.abs(h - Qn[1]).max() < 1e-6, "foam and NumPy disagree"