A differentiable, unstructured, cell-centred finite-volume (FVM) flow solver written in JAX.
Because the entire solver is written in JAX, the gradient of any output — a drag, a mean concentration, an outlet flux — with respect to any input — boundary values, material properties, or the mesh node coordinates themselves — is available by automatic differentiation. That makes sensitivity analysis, gradient-based optimization, inverse problems, and parameter calibration first-class rather than bolt-on, and it lets the solver sit inside a larger differentiable pipeline.
aquaflux grew out of work on water and environmental engineering reactors (ozone/UV/chlorine contactors, clarifiers, digesters) and is designed to couple with aquakin, a differentiable reactive-transport package. Nothing about the solver is specific to that domain, though — it is a general incompressible finite-volume code, and the same machinery applies anywhere you want gradients through a flow solve.
Status: early development (pre-alpha). The core solver works — steady and transient scalar transport, coupled pressure–velocity flow, and k–ω SST turbulence all run and are tested — but the public API is still settling and may change between versions. Not yet published to PyPI.
- Unstructured meshes — a static cell/face/node
Meshwith derived geometry (face areas and normals, cell volumes and centroids). Build structured grids in-process, or import an OpenFOAMpolyMesh. The node coordinates are a differentiable leaf, so gradients flow through the derived geometry — the basis for mesh-sensitivity and shape optimization. - Scalar transport — advection (upwind and slope-limited), diffusion (with
non-orthogonal correction), transient, and volumetric-source operators,
assembled into a residual
R(state, params). - Coupled pressure–velocity flow — the
(u, v[, w], p)block solved monolithically with Rhie–Chow continuity coupling, not segregated SIMPLE/PISO. - k–ω SST turbulence — the RANS closure, coupled to the flow solve through a segregated outer loop.
- Exact adjoints — steady solves converge with a Newton driver whose gradient comes from implicit differentiation (the implicit-function theorem on the converged state plus an adjoint through each linear solve). No solver iteration is unrolled onto the autodiff tape, so gradient cost and accuracy are independent of the iteration count.
- Solvers — Krylov linear solves via lineax, a block preconditioner for the flow saddle-point, algebraic multigrid, and pseudo-transient continuation for high-Reynolds cases (with an optional dual-time / backward-Euler march for a larger, still-stable pseudo-timestep). The coupled RANS saddle is preconditioned by a field split of multigrid hierarchies over the materialized Jacobian.
- Reynolds-number continuation — reach a stiff high-Reynolds root through a
homotopy of easier lower-Reynolds solves, each seeded by the previous one. The
user chooses a single integer (the number of continuation points);
solve_reynolds_continuationderives the schedule, warm-starts each stage, and dissolves the continuation at the target, so the root and its exact adjoint are unchanged. - Swappable numerics — interpolation, gradient reconstruction, and slope limiters are first-class strategy objects with a known order of accuracy, injected into operators and tested in isolation, so the numerics can be changed without touching the physics.
- Ultraviolet radiation and CAD geometry — the fluence rate in the water by an
exact backward gather over emitting surface facets, with absorption, shadowing and
diffuse interreflection. Blocking geometry is described as exact solids
(
aquaflux.solids: cylinders, spheres, cones, their unions, and a vessel as the fluid it holds), and both those solids and a lamp's emitting surface can be read from a STEP drawing withaquaflux.io.cad.read_step, which checks every solid it hands out against the drawing and refuses one it cannot describe exactly. Install the CAD kernel withpip install "aquaflux[cad]". - Distributed memory — domain decomposition (including a SCOTCH partitioner) and halo exchange for a sharded residual.
- Case files — describe a case's mesh, fluid, physics, boundary patches,
numerics and solver in one YAML file (
aquaflux.case.read_case). Each boundary patch is stated once for every field, every setting is checked where it appears, a case can be checked against its mesh without building anything, andaquaflux run case.yamlsolves it and writes its fields (VTK or an OpenFOAM time directory), its log, its convergence history and a record of the run. A case may also be the light of ultraviolet lamps instead of a flow: lamps and reflecting walls on the mesh's patches (their surfaces read from the STEP or STL drawing, or the mesh itself), bodies in the way and an absorbing medium; the run writes the fluence rate in the cells, the irradiance on every wall as one VTK file per patch, and where the lamps' power went. - A browser interface —
aquaflux-uiopens a case file to edit, with every choice taken from the solver's own case-file definitions, or a run's results in a browser page served on your own machine: colour by any field, slice, threshold, step through snapshots, and plot the convergence history. See The browser interface.
aquaflux requires Python ≥ 3.11. Until it is published to PyPI, install from source:
git clone https://github.com/DeGrootResearchGroup/aquaflux
cd aquaflux
pip install -e .Note:
import aquafluxenables JAX 64-bit (x64) mode process-wide. Finite-volume transport and stiff coupling require double precision, so this is an intentional, documented side effect — other JAX code in the same process will use float64 afterward.
On the CPU, aquaflux runs the preconditioner's sparse products as one threaded
Numba loop, which needs a Numba threading layer that several threads may enter at
once (OpenMP or TBB). Numba's macOS wheel includes its OpenMP layer but not the
OpenMP runtime it loads, so a plain pip install on a Mac runs XLA's own form of
those products instead: correct, only without the threaded loop. To enable it,
install the runtime with Homebrew and link it where Numba looks for it:
brew install libomp && brew link --force libompHomebrew does not link libomp by default, so the second command is needed.
Setting DYLD_LIBRARY_PATH is not a substitute: macOS removes it whenever a
shell script starts Python. A conda environment needs neither, since conda's
Numba installs its OpenMP runtime. Each run's run.yaml and log record which form
the products took (padded_products) and why.
A lid-driven cavity: build a mesh, assemble the coupled flow problem, and solve it to convergence.
import aquaflux # enables JAX float64
import jax.numpy as jnp
from aquaflux.boundary import BoundaryConditions
from aquaflux.discretization import FirstOrderUpwind
from aquaflux.flow import (
BlockPreconditioner,
MomentumContinuity,
MovingWall,
NoSlipWall,
PinnedPoint,
)
from aquaflux.mesh import structured_grid_2d
from aquaflux.properties import Constant, PropertyModel
from aquaflux.solve import DampedNewtonStep, RootSolver
def cavity(viscosity):
"""A lid-driven cavity on a 32x32 unit square, parameterized by viscosity."""
mesh = structured_grid_2d(32, 32, lx=1.0, ly=1.0, named_boundaries=True)
return MomentumContinuity.build(
mesh,
mesh.geometry(),
PropertyModel({"viscosity": Constant(viscosity), "density": Constant(1.0)}),
BoundaryConditions(
{
"top": MovingWall(velocity=(1.0, 0.0)),
"bottom": NoSlipWall(),
"left": NoSlipWall(),
"right": NoSlipWall(),
}
),
advection_scheme=FirstOrderUpwind(),
# A closed domain has no outlet to set the pressure level, so it is fixed at a point.
pressure_datum=PinnedPoint((0.0, 0.0)),
)
residual = lambda state, problem: problem.residual(state)
# The block preconditioner accelerates the Krylov solve; build it once and reuse it.
# The strategy is a line-searched Newton step carrying that preconditioner.
precond = BlockPreconditioner.build(cavity(1e-2)).factory()
solver = RootSolver(
max_steps=30, strategy=DampedNewtonStep(preconditioner=precond)
)
problem = cavity(1e-2)
state = solver.solve(residual, problem.initial_state(), problem)
velocity, pressure = problem.unpack(state)The converged solve is differentiable end to end. Here is the sensitivity of a flow functional to the viscosity — one exact adjoint, with no unrolled iterations:
import jax
def mean_speed(viscosity):
problem = cavity(viscosity)
state = solver.solve(residual, problem.initial_state(), problem)
velocity, _ = problem.unpack(state)
return jnp.mean(jnp.abs(velocity[:, 0]))
gradient = jax.grad(mean_speed)(1e-2)The same works for gradients with respect to boundary values, source terms, or the mesh node coordinates.
aquaflux-ui shows a run's results in your browser — the Setup and Run sections
beside them hold the places of case setup and running. It is an optional extra —
VTK (through PyVista) renders, trame serves the page, plotly draws the plot — with
wheels for Linux, macOS and Windows, so it needs no compiler and no JavaScript
toolchain:
pip install -e ".[ui]"
aquaflux-ui path/to/results # the directory `aquaflux run` wrote
aquaflux-ui fields.vtu # or a .vtu, .pvd, .vtp or .vtm fileIt serves the page on 127.0.0.1 only and opens it in the default browser
(--no-browser prints the address instead, --port picks the port). The side
panel shows the run's record and chooses what is drawn: the dataset, the field it
is coloured by (a vector's magnitude or one component), the colormap, a linear or
logarithmic scale with an automatic or fixed range, the outer surface and its
opacity, any number of slice planes normal to x, y or z and any number of
threshold regions (each with a slider and a box to type its coordinate or limits
exactly), and the snapshot of a time series. Below the view, the convergence
history plots the residual against the step; Reload re-reads it, so a run still
in progress can be followed.
The scene is rendered on your machine and the browser receives images, so a mesh of millions of cells is never sent to it, and what is drawn of a volume is its outer surface, the slices and the threshold regions rather than every cell. The viewer reads files only: it imports neither aquaflux nor JAX, and aquaflux never imports it, so results copied to another machine open there with only the extra installed.
Full documentation — the mesh model, zones and patches, steady-state solving, and the API reference — is at aquaflux.readthedocs.io.
pip install -e ".[lint,test]"
# Optional: enable the local ruff pre-push gate (opt-in, once per clone).
# Keep the path relative -- git resolves it from the top of the working tree, so it
# follows each checkout (and each worktree) to its own .githooks/.
git config core.hooksPath .githooks
ruff check aquaflux aquaflux_ui tests docs
ruff format --check aquaflux aquaflux_ui tests docs
pytest -m "not validation and not slow" # fast gateThe full test suite includes scientific validation cases (marked validation)
and multi-minute solves (marked slow); the command above runs the fast gate.
The same ruff checks run in CI on every pull request.
MIT © Christopher T. DeGroot