Steady and unsteady Stokes in a divergence-free space¶
You will learn: to declare coupled velocity and pressure fields, assign a divergence-free velocity space, and inspect pressure-gradient error. Prerequisites: divergence-free kernels and time discretization.
Steady Stokes momentum is
Unsteady momentum adds \(\partial_t\boldsymbol u\). The manufactured example uses \(\mu=1\), \(\boldsymbol u=(e^{-t}y(1-y),0)\), and \(p=-2x\); the steady version omits the exponential. Boundary values and forcing are derived from these fields.
Complete runnable script
"""Steady and unsteady Stokes with an explicit divergence-free velocity space.
Run: python -m examples.tutorials.stokes_spaces
"""
import numpy as np
import sympy as sp
import rbflab as rbf
def make_problem(transient):
model = rbf.SymbolicStokes(
2,vector_fields=("U",), scalar_fields=("p",), transient=transient,
)
U, p = model.fields
x, y = model.coordinates
velocity = sp.ImmutableMatrix([y*(1-y), 0])
if transient:
velocity = sp.exp(-model.time)*velocity
pressure = -2*x
momentum = -model.laplacian(U) + model.gradient(p)
if transient:
momentum += sp.diff(U, model.time)
forcing = momentum.subs(dict(zip(U, velocity)) | {p: pressure}).doit()
boundary = [model.bc("boundary", sp.Eq(U, velocity))]
if transient:
problem = model.evolution(
[sp.Eq(momentum, forcing)],
initial={U: velocity.subs(model.time, 0)},
boundary=boundary,
)
else:
problem = model.stationary([sp.Eq(momentum, forcing)], boundary=boundary)
spaces = rbf.MixedSpace({
U: rbf.DivergenceFreeSpace(rbf.IMQ(2), 2),
p: rbf.PressureSpace(rbf.IMQ(2), 1),
})
return problem, spaces
def run(cells=4):
cloud = rbf.geometry.unit_box_grid(cells)
query = np.array([[0.3, 0.4]])
results = {}
for transient in (False, True):
problem, spaces = make_problem(transient)
method = rbf.GlobalCollocation(spaces=spaces)
system = method.assemble(problem, cloud)
solution = (system.solve("0.01", 3, scheme="bdf2").final
if transient else system.solve())
time = 0.03 if transient else 0.0
expected_velocity = np.array([[np.exp(-time)*0.4*0.6, 0.]])
velocity_error = float(np.max(np.abs(solution.velocity(query)-expected_velocity)))
gradient_error = float(np.max(np.abs(solution.pressure_gradient(query)-[-2., 0.])))
divergence = float(np.max(np.abs(solution.divergence(query))))
name = "unsteady" if transient else "steady"
results[name] = (velocity_error, gradient_error, divergence)
print(f"{name}: system={system.matrix.shape}, velocity_error={velocity_error:.3e}, "
f"pressure_gradient_error={gradient_error:.3e}, divergence={divergence:.3e}")
return results
if __name__ == "__main__":
run()
Run python -m examples.tutorials.stokes_spaces. Velocity uses the matrix kernel \(\nabla\nabla^{\mathsf T}\phi-I\Delta\phi\), which is divergence-free by construction. The symbolic system supplies momentum equations but no redundant divergence equation. Pressure is defined up to a constant, so the example checks \(\nabla p\), not an absolute pressure value.
For the 25-node cloud, both global systems were \(61\times61\). A verified steady query had velocity error \(1.482\times10^{-17}\), pressure-gradient error \(4.521\times10^{-16}\), and reported divergence zero. At \(t=0.03\), the short BDF2 run had velocity error \(1.271\times10^{-7}\), pressure-gradient error \(3.296\times10^{-6}\), and reported divergence zero. These are single-query errors, not domain norms.
BDF2 starts with one backward Euler step. The initial condition sets velocity, not pressure. Try changing \(\mu\) and rederive forcing. See equations and spaces.
A simple local Stokes example¶
examples/stokes_lhi_baseline.py follows five steps: choose an exact solution,
derive its forcing, declare the kernels and spaces, assemble LHI, then compare
the nodal solution with the exact fields. It uses homogeneous walls, 37-point
stencils, velocity/pressure augmentation 6/1 and the fully mesh-scaled kernels
with pressure coefficient cbar_p=1.
python -m examples.stokes_lhi_baseline
python -m examples.stokes_lhi_baseline --ranks 2
The default is a small 81-node example with C++ weights. MPI requires a launcher
as described in installation. Both time steps run to T=0.1;
the printed errors are absolute vector RMS values at interior mesh nodes.
The coarse default demonstrates the workflow; use the fine meshes to study
the accuracy of the baseline.
For the larger meshes, use --cells 89 (8,100 nodes) or --cells 126
(16,129 nodes). This direct teaching route constructs every stencil and can
take substantially longer than a specialized batched reproduction driver.
Complete local Stokes script
"""Unsteady Stokes: homogeneous walls, exact solution, and nodal errors.
Small example (requires the C++ toolchain):
python -m examples.stokes_lhi_baseline
The two baseline meshes, with MPI local weights:
python -m examples.stokes_lhi_baseline --cells 89 --ranks 8
python -m examples.stokes_lhi_baseline --cells 126 --ranks 8
This teaching script calls LHI directly. Large runs construct every stencil;
the measured batch/checkpoint driver is in research/divfree_lhi_energy/.
"""
import argparse
from fractions import Fraction
import numpy as np
import sympy as sp
from threadpoolctl import threadpool_limits
import rbflab as r
def run(cells=8, ranks=1, end_time="0.1", backend="cpp", digits=80):
# 1. Choose an exact divergence-free velocity and its pressure.
model = r.SymbolicStokes(2, transient=True)
u, p = model.fields
x, y = model.coordinates
t = model.time
psi = 256*x**2*(1-x)**2*y**2*(1-y)**2
exact_u = sp.exp(-t)*sp.Matrix([sp.diff(psi, y), -sp.diff(psi, x)])
exact_p = sp.exp(-t)*(x-y)
# 2. Derive the forcing for u_t - Laplacian(u) + grad(p) = f.
momentum = sp.diff(u, t)-model.laplacian(u)+model.gradient(p)
forcing = momentum.subs(dict(zip(u, exact_u)) | {p: exact_p}).doit()
problem = model.evolution(
[sp.Eq(momentum, forcing)],
initial={u: exact_u.subs(t, 0)},
boundary=[model.bc("boundary", sp.Eq(u, sp.zeros(2, 1)))],
)
# 3. Full h-scaling, with cbar_p = 1. Here s denotes r**2.
q = sp.Rational(cells, 44) # q = (1/44)/h, where h = 1/cells
velocity_kernel = r.Hybrid(r.Gaussian(10*q*q), r.PHS(7), q**7)
s = sp.Symbol("s", nonnegative=True)
pressure_kernel = r.Kernel(q**4*sp.exp(-q*q*s), s)()
spaces = r.MixedSpace({
u: r.DivergenceFreeSpace(velocity_kernel, polynomial_degree=6),
p: r.PressureSpace(pressure_kernel, polynomial_degree=1),
})
# 4. Assemble once; reuse the same matrices for both time steps.
numerical_backend = (r.CppBackend(threads=1, timeout=3600)
if backend == "cpp" else r.PythonBackend())
execution = r.LocalExecution(scheduler="mpi", ranks=ranks) if ranks > 1 else None
method = r.LHI(
spaces=spaces, stencil_size=37,
precision=r.Precision(local_digits=digits),
stencil_policy=r.StencilPolicy(scaling="physical"),
local_backend=numerical_backend, execution=execution,
)
cloud = r.geometry.unit_box_grid(cells)
system = method.assemble(problem, cloud)
# 5. Measure absolute vector errors only at interior mesh nodes.
points = cloud.interior
final_time = float(Fraction(end_time))
truth = sp.lambdify((x, y), exact_u.subs(t, final_time), "numpy")
velocity_exact = np.asarray(truth(points[:, 0], points[:, 1]), dtype=float).reshape(2, -1).T
gradient_exact = np.tile(np.exp(-final_time)*np.array([1., -1.]), (len(points), 1))
results = []
for dt in ("0.00025", "0.000125"):
steps = Fraction(end_time)/Fraction(dt)
if steps.denominator != 1 or steps < 1:
raise ValueError("end_time must be a positive multiple of both time steps")
solution = system.solve(dt=dt, steps=int(steps), time_scheme="bdf2").states[-1]
velocity_error = np.linalg.norm(solution.velocity(points)-velocity_exact, axis=1)
gradient_error = np.linalg.norm(solution.pressure_gradient(points)-gradient_exact, axis=1)
result = {
"dt": float(dt),
"velocity_rms": float(np.sqrt(np.mean(velocity_error**2))),
"gradient_rms": float(np.sqrt(np.mean(gradient_error**2))),
"velocity_max": float(velocity_error.max()),
"gradient_max": float(gradient_error.max()),
}
results.append(result)
print(f"nodes={len(cloud.points)}, dt={dt}: "
f"velocity RMS={result['velocity_rms']:.6e}, "
f"pressure-gradient RMS={result['gradient_rms']:.6e}")
return results
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cells", type=int, default=8)
parser.add_argument("--ranks", type=int, default=1)
parser.add_argument("--backend", choices=("python", "cpp"), default="cpp")
parser.add_argument("--digits", type=int, default=80)
parser.add_argument("--end-time", default="0.1")
args = parser.parse_args()
if args.ranks > 1 and args.backend != "cpp":
parser.error("MPI local weights require --backend cpp")
with threadpool_limits(limits=1):
run(args.cells, args.ranks, args.end_time, args.backend, args.digits)
To inspect a single local weight construction, start with
python -m examples.stokes_lhi_weights. It shows MixedSpace, FieldOperator,
Samples and LocalApproximation directly. Add --backend cpp --digits 80 --mpi 2
for native MPI weights. The simpler two-scalar-field example is
python -m examples.mixed_local_maps.
Navier-Stokes with explicit local assembly¶
examples/navier_stokes_lhi.py builds the matrices directly with the public
LocalApproximation API and advances the solution with SciPy:
python -m examples.navier_stokes_lhi --cells 8 --nu 1 --ranks 2
The example declares MixedSpace and unpacks u, p = space.fields.
One Stencil(points, size=37) is shared by interior velocity, boundary
velocity and neighboring momentum samples; momentum excludes the target.
The mixed maps give A, B, SL, PY, PB and PL, with M = I - SL.
A separate degree-5 divergence-free value reconstruction gives interior
Dx, Dy and boundary Dxb, Dyb blocks on the same 37 sites.
All vector blocks use node-major ordering. Prescribed boundary data enter
momentum as -B @ g(t), pressure recovery as PB @ g(t), and convection
derivatives as Dx @ U + Dxb @ g(t) and Dy @ U + Dyb @ g(t).
The example uses 6/1 mixed augmentation, full h-scaled kernels and 80-digit
native weights with MPI. Backward Euler starts BDF2 with explicitly
extrapolated numerical convection. Both time steps reach T=0.1, and only
interior-nodal absolute vector RMS and maximum errors are measured. The small
default mesh illustrates the workflow; it is not a fine-grid accuracy claim.
Changing viscosity rebuilds the mixed weights. The global SciPy solve is
serial, and locally divergence-free reconstructions do not impose global
divergence conformity. The manufactured velocity includes a constant spatial
offset multiplied by exp(-t), giving nonzero time-dependent boundary data.
Use --offset 0 to recover homogeneous walls. This example does not implement
the cavity wall and corner treatment.
The 81-node viscosity-1 example with the default offset completed both time
steps with velocity RMS about 0.009930 and pressure-gradient RMS about 0.6587.
The previous homogeneous-wall case gave about 0.01025 and 0.6585 respectively.
A viscosity-0.1 homogeneous-wall trial on this coarse mesh became nonfinite
at step 109 with dt=0.00025; do not use
that configuration as a stable baseline. Fine-grid results require separate
runs and are not inferred from this example.
Complete local Navier-Stokes script
"""Mixed LHI Navier-Stokes with prescribed time-dependent boundary velocity, using only public APIs.
python -m examples.navier_stokes_lhi --cells 8 --ranks 2
Requires the optional C++/MPFR toolchain and MPI launcher. The small default
mesh demonstrates the method; it is not the fine-grid accuracy benchmark.
All vectors use node-major order: [ux_0, uy_0, ux_1, uy_1, ...].
"""
import argparse
import numpy as np
import sympy as sp
from scipy.sparse import eye
from scipy.sparse.linalg import factorized
from threadpoolctl import threadpool_limits
import rbflab as r
def assemble(cells, nu, ranks):
# 1. One shared 37-site physical stencil, partitioned by sample group.
cloud = r.geometry.unit_box_grid(cells)
points, targets = cloud.points, cloud.interior
boundary = points[cloud.boundary_indices]
stencil = r.Stencil(points, size=37)
# 2. Full h-scaling; the kernels act on physical coordinates.
q = sp.Rational(cells, 44)
velocity_kernel = r.Hybrid(r.Gaussian(10*q*q), r.PHS(7), q**7)
s = sp.Symbol("s", nonnegative=True) # squared distance
pressure_kernel = r.Kernel(q**4*sp.exp(-q*q*s), s)()
space = r.MixedSpace({
"u": r.DivergenceFreeSpace(velocity_kernel, polynomial_degree=6),
"p": r.PressureSpace(pressure_kernel, polynomial_degree=1),
})
u, p = space.fields
value = u
momentum = -nu*r.laplacian(u) + r.gradient(p)
pressure_gradient = r.gradient(p)
options = dict(backend=r.CppBackend(threads=1, timeout=3600),
execution=r.LocalExecution(scheduler="mpi", ranks=ranks),
precision=r.Precision(local_digits=80))
# 3. Separate interior, boundary and neighboring momentum observations.
source = {
"velocity": r.Samples(targets, operator=u, within=stencil),
"boundary": r.Samples(boundary, operator=u, within=stencil),
"momentum": r.Samples(targets, operator=momentum,
within=stencil, target="exclude"),
}
local = r.LocalApproximation(source=source, trial=space.representers(source), **options)
maps = local.operators(targets=targets,
operators={"L": momentum, "P": pressure_gradient})
# M U_t + A U = M(f - C) - B g(t).
A = maps.L["velocity"].to_scipy()
B = maps.L["boundary"].to_scipy()
SL = maps.L["momentum"].to_scipy()
M = eye(A.shape[0], format="csr") - SL
PY = maps.P["velocity"].to_scipy()
PB = maps.P["boundary"].to_scipy()
PL = maps.P["momentum"].to_scipy()
# 4. Separate degree-5 divergence-free, value-only reconstruction.
# Both components are coupled; these are not scalar differentiation maps.
convection_space = r.MixedSpace({
"u": r.DivergenceFreeSpace(velocity_kernel, polynomial_degree=5)})
values = {
"velocity": r.Samples(targets, operator=value, within=stencil),
"boundary": r.Samples(boundary, operator=value, within=stencil),
}
reconstruction = r.LocalApproximation(
source=values, trial=convection_space.representers(values), **options)
derivatives = reconstruction.operators(targets=targets, operators={
"dx": r.dx(u),
"dy": r.dy(u),
})
Dx = derivatives.dx["velocity"].to_scipy()
Dxb = derivatives.dx["boundary"].to_scipy()
Dy = derivatives.dy["velocity"].to_scipy()
Dyb = derivatives.dy["boundary"].to_scipy()
print(f"Built mixed and convection maps for {len(points)} nodes with {ranks} MPI ranks.")
return targets, boundary, M, A, B, PY, PB, PL, Dx, Dxb, Dy, Dyb
def manufactured_solution(points, boundary, nu, offset=1):
# 5. Exact velocity, pressure gradient and Navier-Stokes forcing.
x, y = sp.symbols("x y")
psi = 256*x**2*(1-x)**2*y**2*(1-y)**2
v = sp.Matrix([sp.diff(psi, y) + offset, -sp.diff(psi, x) - offset])
lap = v.diff(x, 2) + v.diff(y, 2)
nonlinear = v.jacobian([x, y])*v
def sample(expressions, nodes=points):
return np.column_stack([np.broadcast_to(
sp.lambdify((x, y), e, "numpy")(*nodes.T), (len(nodes),))
for e in expressions]).ravel()
U0 = sample(v)
G0 = sample(sp.Matrix([1, -1]))
F1 = sample(-v - nu*lap + sp.Matrix([1, -1]))
F2 = sample(nonlinear)
forcing = lambda t: np.exp(-t)*F1 + np.exp(-2*t)*F2
boundary_initial = sample(v, boundary)
boundary_velocity = lambda t: np.exp(-t)*boundary_initial
return U0, G0, forcing, boundary_velocity
def evolve(M, A, B, PY, PB, PL, Dx, Dxb, Dy, Dyb,
U0, forcing, boundary_velocity, dt, steps):
# 6. Implicit diffusion/pressure, explicit extrapolated convection.
def convection(U, t):
v = U.reshape(-1, 2)
g = boundary_velocity(t)
ux = (Dx @ U + Dxb @ g).reshape(-1, 2)
uy = (Dy @ U + Dyb @ g).reshape(-1, 2)
return (v[:, :1]*ux + v[:, 1:]*uy).ravel()
be = factorized((M/dt + A).tocsc())
bdf2 = factorized((1.5*M/dt + A).tocsc())
U = U0.copy()
C = convection(U, 0)
for k in range(1, steps+1):
if k == 1:
Cstar, history, alpha, solve = C, U/dt, 1/dt, be
else:
Cstar = 2*C - C_previous
history, alpha, solve = (2*U - .5*U_previous)/dt, 1.5/dt, bdf2
force = forcing(k*dt) - Cstar
g = boundary_velocity(k*dt)
U_new = solve(M @ (history + force) - B @ g)
U_t = alpha*U_new - history
grad_p = PY @ U_new + PB @ g + PL @ (force - U_t)
if not (np.isfinite(U_new).all() and np.isfinite(grad_p).all()):
raise FloatingPointError(f"Nonfinite field at step {k}")
U_previous, U = U, U_new
C_previous, C = C, convection(U_new, k*dt)
return U, grad_p
def run(cells=8, nu=1.0, ranks=2, end_time="0.1", offset=1):
# 7. Reuse weights for both time steps; errors only at interior mesh nodes.
duration = sp.Rational(end_time)
dts = (sp.Rational("0.00025"), sp.Rational("0.000125"))
if any(duration/dt < 1 or (duration/dt).denominator != 1 for dt in dts):
raise ValueError("end_time must be a positive multiple of both time steps")
points, boundary, M, A, B, PY, PB, PL, Dx, Dxb, Dy, Dyb = assemble(cells, nu, ranks)
U0, G0, forcing, boundary_velocity = manufactured_solution(points, boundary, nu, offset)
results = []
for dt in dts:
U, G = evolve(M, A, B, PY, PB, PL, Dx, Dxb, Dy, Dyb,
U0, forcing, boundary_velocity, float(dt), int(duration/dt))
row = {"dt": float(dt)}
for name, field, exact in (("velocity", U, U0), ("gradient", G, G0)):
error = (field - np.exp(-float(duration))*exact).reshape(-1, 2)
lengths = np.linalg.norm(error, axis=1)
row[name + "_rms"] = float(np.sqrt(np.mean(lengths**2)))
row[name + "_max"] = float(lengths.max())
print(row, flush=True)
results.append(row)
return results
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cells", type=int, default=8)
parser.add_argument("--nu", type=float, default=1.0)
parser.add_argument("--ranks", type=int, default=2)
parser.add_argument("--end-time", default="0.1")
parser.add_argument("--offset", type=float, default=1,
help="Constant velocity offset; 0 recovers homogeneous walls")
args = parser.parse_args()
with threadpool_limits(limits=1):
run(args.cells, args.nu, args.ranks, args.end_time, args.offset)
For readable research implementations of alternative Navier–Stokes time schemes,
see research/navier_stokes_schemes/README.md in the repository. The comparison
includes coupled Oseen/Newton BDF2, midpoint and ARS IMEX variants, rotational
convection, characteristics, and an experimental rebuilt Oseen Hermite closure.
These are research drivers, not additional stable package solver APIs. Their
coarse verification runs must not be confused with the fine-grid baseline.
Native global fields¶
For the local Stokes method in source version 0.6.0, see
shared local weight construction.
Python/C++ LU LHI(spaces=...) now uses LocalApproximation for weights, while
retaining the compact mass matrix and local pressure-gradient output. Add
execution=LocalExecution(scheduler="mpi", ranks=2) with CppBackend to
distribute those local weights. This does not select a native global solver or
introduce a scalar pressure gauge field.
For fixed kernel parameters, this C++ LU path also accepts
stencil_policy=StencilPolicy(scaling="local"), including with MPI. Its radius
is measured from each target to the selected source points, matching Python
Stokes LHI. Returned derivatives already include their physical scaling factors.
Keep physical coordinates when reproducing a recipe whose kernel parameters
already include the desired mesh scaling. Native SVD and historical custom
executables retain their physical-coordinate requirement.
The stationary problem above can use C++ for kernel and polynomial assembly, LU, repeated solves, and field evaluation. Select the backend on the same method:
from examples.tutorials.stokes_spaces import make_problem
import rbflab as rbf
problem, spaces = make_problem(transient=False)
method = rbf.GlobalCollocation(
spaces=rbf.MixedSpace(spaces),
precision=rbf.Precision(global_digits=60), # omit global_digits for double
backend=rbf.CppGlobalBackend(threads=2),
)
cloud = rbf.geometry.unit_box_grid(4)
with method.assemble(problem, cloud) as system:
solution = system.solve()
velocity = solution.velocity([[.3, .4]], extended=True)
gradient = solution.pressure_gradient([[.3, .4]], extended=True)
divergence = solution.divergence([[.3, .4]], extended=True)
pressure = solution.pressure(
[[.3, .4]], reference=([0., 0.], 0), extended=True,
)
momentum_error = solution.residuals([[.3, .4]], extended=True)
DivergenceFreeSpace applies the matrix-valued kernel transform to the velocity
potential; pressure has its own scalar potential. Each potential can use a
different supported kernel family and parameter values. Velocity polynomial
columns lie in the exact divergence-free nullspace. Pressure polynomials omit
the constant mode, so prescribing a reference shifts the evaluated pressure
without adding a gauge equation to the matrix.
This native path supports steady and unsteady symmetric Stokes in 2D and 3D with
constant viscosity and prescribed velocity boundaries, with or without
polynomial augmentation. Asymmetric field collocation, general mixed-vector
equations and coupled scalar blocks are not supported. Kernel derivatives through total
order six cover native velocity values, first/second derivatives and momentum
residuals; derivative_order above two is rejected for native Stokes.
Field methods return NumPy arrays by default. With global_digits set,
extended=True retains mpmath output converted directly from MPFR decimal
results. Geometry still starts as Float64. Evaluate before closing the system;
RHS edits reuse the native factors, and matrix edits invalidate them.
For unsteady Stokes, use make_problem(transient=True) and the same backend:
problem, spaces = make_problem(transient=True)
method = rbf.GlobalCollocation(
spaces=rbf.MixedSpace(spaces),
backend=rbf.CppGlobalBackend(threads=2),
)
with method.assemble(problem, cloud) as system:
trajectory = system.solve(dt="0.01", steps=100, scheme="bdf2")
velocity = trajectory.final.velocity([[.3, .4]])
gradient = trajectory.final.pressure_gradient([[.3, .4]])
A = system.matrix.to_numpy() # explicit export of native stiffness
M = system.mass.to_numpy() # explicit export; read-only native mass
b = system.data(1.0)
The native worker assembles A and M for M c_dot + A c = b(t). Only
interior velocity rows have mass; boundary and polynomial constraint rows have
zero mass. Python evaluates forcing and boundary data at each time in the
selected precision. Backward Euler and BDF2 perform native LU solves and mass
products without exporting either dense matrix. BDF2 starts with backward
Euler; fixed time steps reuse two shifted factorizations. Up to four shifts
are cached per system. Editing system.matrix invalidates these factors;
system.mass is read-only. system.matrix remains the stiffness matrix after
time stepping. Use .to_mpmath() for explicit extended-precision matrix export.
The trajectory and all its field predictions require the system to remain open.
Run python -m examples.global_cpp_unsteady --power 9 --digits 40 for a
manufactured IMQ + PHS r9 velocity / r5 pressure example. Its three-query errors
include both spatial and time discretization error; they are not domain norms.
Run python -m examples.global_cpp_fields for a double check, or
python -m examples.global_cpp_fields --dimension 3 --digits 60 for extended
arithmetic. This example measures reproduction of a quadratic divergence-free
field and linear pressure at five off-node points, not general convergence.