Skip to content

Build a lid-driven cavity solver

Goal: assemble a coupled nonlinear evolution algorithm from reusable maps. First work through custom sparse assembly, heat time stepping, and coupled fields. This lesson uses scalar velocity spaces and a separate continuity equation.

Computed cavity velocity at Re 100

This example shows how to build a nonlinear time-dependent algorithm from RBFLAB's source-to-target RBF-FD matrices. We follow the actual implementation in examples/navier_stokes_cavity.py, from the point sets to the sparse block solve. The animation uses 800 velocity nodes, 289 pressure nodes and \(t=20\); it is an illustration, not a grid-converged benchmark.

1. Model and boundary data

With unit density, solve on \(\Omega=(0,1)^2\):

\[\partial_t\boldsymbol u+(\boldsymbol u\cdot\nabla)\boldsymbol u -\nu\Delta\boldsymbol u+\nabla p=0,\qquad \nabla\cdot\boldsymbol u=0.\]

The top lid has \((u,v)=(1,0)\); the other three walls have \((0,0)\). The interior starts at rest, with the lid applied immediately. Unit length and lid speed give \(\mathrm{Re}=1/\nu=100\) for \(\nu=0.01\). The abrupt lid/side transition creates a corner singularity; this example does not smooth or ramp the lid.

Velocity components use scalar RBF spaces here. They are not divergence-free by construction. Incompressibility is represented through a separate block of discrete equations. This differs from the divergence-free Stokes example.

2. Two point sets and three operator maps

The square is split into triangles. Pressure nodes are its vertices; velocity nodes are the midpoints of unique triangle edges, including the diagonals. For cells=c, there are \((c+1)^2\) pressure nodes and \(3c^2+2c\) velocity nodes. Boundary velocity midpoints avoid placing a velocity unknown exactly at a corner.

Vertices and edge midpoints illustrate the staggered locations

The picture explains the construction on two triangles. The solver's regular square uses the same unique-edge idea. Here is its complete cloud construction:

Construct the cavity clouds
def clouds(cells):
    """Vertices carry pressure; triangle edge midpoints carry velocity."""
    pressure = r.geometry.unit_box_grid(cells)
    node = np.arange((cells + 1) ** 2).reshape(cells + 1, cells + 1)
    a, b = node[:-1, :-1].ravel(), node[1:, :-1].ravel()
    c, d = node[1:, 1:].ravel(), node[:-1, 1:].ravel()
    triangles = np.vstack((np.column_stack((a, b, c)),
                           np.column_stack((a, c, d))))
    edges = np.vstack((triangles[:, [0, 1]], triangles[:, [1, 2]],
                       triangles[:, [2, 0]]))
    edges = np.unique(np.sort(edges, axis=1), axis=0)
    points = pressure.points[edges].mean(axis=1)
    sides = (("left", 0, 0, -1), ("right", 0, 1, 1),
             ("bottom", 1, 0, -1), ("top", 1, 1, 1))
    boundary, normals = {}, {}
    for name, axis, value, sign in sides:
        ids = np.flatnonzero(np.isclose(points[:, axis], value))
        normal = np.zeros(2); normal[axis] = sign
        boundary[name] = ids
        normals[name] = np.tile(normal, (len(ids), 1))
    return r.PointCloud(points, boundary, normals), pressure

PHS7, polynomials through degree three, and 28-node stencils are used for both fields. PressureSpace describes the pressure approximation; it does not impose the mean constraint used later.

    velocity, pressure = clouds(cells)
    rbffd = r.RBFFD(spaces=r.MixedSpace({"u": r.ScalarSpace(r.PHS(7), 3),
                                         "p": r.PressureSpace(r.PHS(7), 3)}),
                    stencil_size=28, local_backend=local)
    differential = {"dx": r.Derivative(0), "dy": r.Derivative(1),
                    "lap": r.Laplacian()}
    def operators(source, target, space):
        return rbffd.operators(source=source, targets=target, space=space,
                               operators=differential)
    vv = operators(velocity, velocity, "u")
    vp = operators(velocity, pressure, "u")
    pv = operators(pressure, velocity, "p")
    dx, dy, lap = (vv[name].matrix for name in ("dx", "dy", "lap"))
    Dx, Dy = vp.dx.matrix, vp.dy.matrix
    Gx, Gy = pv.dx.matrix, pv.dy.matrix

These statements are inside solve; local is its selected Python or C++ backend. Read a map name as source, target:

Code Source values Evaluation locations Matrix dimensions
vv.dx, vv.dy, vv.lap Velocity nodes Velocity nodes \(N_v\times N_v\)
vp.dx, vp.dy Velocity nodes Pressure nodes \(N_p\times N_v\)
pv.dx, pv.dy Pressure nodes Velocity nodes \(N_v\times N_p\)

Write \(d_x,d_y,L\) for the first row, \(D_x,D_y\) for the second, and \(G_x,G_y\) for the third. The same scalar operators act on both velocity components. These are independently constructed collocation maps: \(D\) is not imposed as \(-G^T\). The example does not assemble a pressure Poisson matrix or perform a projection step.

3. Discretize convection and diffusion

At velocity nodes, the advective form is

\[C^n=\operatorname{diag}(u^n)d_xU^n+\operatorname{diag}(v^n)d_yU^n,\]

where \(U^n\) is the \(N_v\times2\) array of velocity components. In code: u[:,0,None]*(dx @ u) + u[:,1,None]*(dy @ u). There is no upwinding, hyperviscosity or skew-symmetric energy correction in this example.

Use Adams–Bashforth extrapolation \(\widehat C^{n+1/2}=\tfrac32C^n-\tfrac12C^{n-1}\), with \(\widehat C^{1/2}=C^0\) for startup. Crank–Nicolson diffusion gives

\[A=\Delta t^{-1}I-\tfrac{\nu}{2}L,\qquad B=\Delta t^{-1}I+\tfrac{\nu}{2}L,\]
\[AU^{n+1}+G\pi=B U^n-\widehat C^{n+1/2}.\]

Here \(G\pi\) means the two columns \((G_x\pi,G_y\pi)\). The pressure unknown \(\pi\) is the multiplier for this time step (naturally a midpoint pressure in the CN momentum equation); it is not advanced through an independent pressure evolution formula. Explicit convection still restricts usable time steps.

4. Eliminate wall velocities

Let \(I\) index interior velocity nodes and \(W\) index wall velocity nodes. The known wall array is \(U_W=(g_u,g_v)\). Define

\[r_u=(BU^n)_{I,1}-\widehat C_{I,1}-A_{IW}g_u,\qquad r_v=(BU^n)_{I,2}-\widehat C_{I,2}-A_{IW}g_v,\]
\[c=-D_{x,W}g_u-D_{y,W}g_v.\]

fixed stores the full prescribed wall array. The top label sets its horizontal component to one. correction is \(A_{IW}U_W\); continuity is \(c\). No separate pressure boundary rows are imposed: all pressure locations, including boundary vertices, supply continuity rows; momentum is imposed at interior velocity nodes.

5. Solve velocity and pressure together

With \(a=A_{II}\) and \(\boldsymbol1\in\mathbb R^{N_p}\), each step solves

\[ \begin{bmatrix} a&0&G_{x,I}&0\\ 0&a&G_{y,I}&0\\ D_{x,I}&D_{y,I}&0&\boldsymbol1\\ 0&0&\boldsymbol1^T&0 \end{bmatrix} \begin{bmatrix}u_I^{n+1}\\v_I^{n+1}\\\pi\\\lambda\end{bmatrix} = \begin{bmatrix}r_u\\r_v\\c\\0\end{bmatrix}. \]

The final row fixes the arithmetic mean of pressure to zero; it is not a quadrature-weighted integral constraint. The additional column introduces a compatibility multiplier \(\lambda\). The system has \(2N_I+N_p+1\) unknowns. Here is the actual assembly and boundary elimination:

    inside, wall = velocity.interior_indices, velocity.boundary_indices
    n, m = len(velocity.points), len(pressure.points)
    viscosity = .01  # Re = lid speed * box width / viscosity = 100
    # CN diffusion: A multiplies u^{n+1}, B multiplies u^n.
    A = eye(n, format="csr") / dt - .5 * viscosity * lap
    B = eye(n, format="csr") / dt + .5 * viscosity * lap
    a = A[inside][:, inside]
    zero = csr_matrix(a.shape)
    ones = csr_matrix(np.ones((m, 1)))
    # Unknowns: [u_I, v_I, pressure, compatibility multiplier].
    # Last row fixes the arithmetic pressure mean; the column of ones allows
    # D_x u + D_y v = -lambda at every pressure node, not exactly zero.
    coupled = bmat([[a, zero, Gx[inside], None],
                    [zero, a, Gy[inside], None],
                    [Dx[:, inside], Dy[:, inside], None, ones],
                    [None, None, ones.T, None]], format="csc")
    factor = splu(coupled)
    fixed = np.zeros((n, 2))
    fixed[velocity.boundary["top"], 0] = 1.
    # Eliminate the known velocity boundary values from momentum/continuity.
    correction = A[inside][:, wall] @ fixed[wall]
    continuity = -Dx[:, wall] @ fixed[wall, 0] - Dy[:, wall] @ fixed[wall, 1]

The LU factorization is reusable because the cloud, viscosity and time step stay fixed and convection is explicit. Changing these matrix-defining quantities requires rebuilding the factorization. For time-dependent wall data, refresh both boundary right-hand-side contributions at each step.

Why the reported divergence is not zero

Restoring boundary values in the third block row gives

\[D_xu^{n+1}+D_yv^{n+1}=-\lambda\boldsymbol1.\]

Therefore a small linear residual can coexist with a nonzero divergence defect. The multiplier is not a pressure gauge by itself: it allows the continuity system to absorb a spatially constant incompatibility. The separate last row fixes the pressure gauge. This algebra does not prove inf–sup stability or pressure accuracy.

6. Follow the full time loop

    u = fixed.copy()
    previous = None
    times, samples = [0.], [u.copy()]
    stride = max(1, steps // (frames - 1))
    for step in range(1, steps + 1):
        # Advective (not conservative/skew-symmetric) convection, evaluated at velocity nodes.
        convection = u[:, 0, None] * (dx @ u) + u[:, 1, None] * (dy @ u)
        explicit = convection if previous is None else 1.5 * convection - .5 * previous
        rhs = B[inside] @ u - explicit[inside] - correction
        # Reuse the same sparse LU because dt, viscosity and nodes are fixed.
        answer = factor.solve(np.r_[rhs[:, 0], rhs[:, 1], continuity, 0.])
        new = fixed.copy()
        new[inside, 0] = answer[:len(inside)]
        new[inside, 1] = answer[len(inside):2 * len(inside)]
        if not np.isfinite(new).all() or np.max(np.abs(new)) > 5:
            raise RuntimeError(f"Cavity solve became unstable at t={step * dt:g}")
        u, previous = new, convection
        if step % stride == 0 or step == steps:
            times.append(step * dt)
            samples.append(u.copy())

The solution vector is ordered as interior horizontal velocity, interior vertical velocity, all pressure values, then \(\lambda\). The code copies the wall data back and saves selected velocity frames. The max(abs(new)) > 5 check is a runaway safeguard, not a stability criterion. Pressure is computed at every step but the function returns velocity history and final pressure diagnostics, not a pressure trajectory.

7. Run a short check before a long animation

From a source checkout:

python -m examples.tutorials.cavity --cells 6 --end 0.005
python -m examples.tutorials.cavity --cells 6 --end 0.005 --output outputs/startup.gif

The short case uses 120 velocity nodes, 49 pressure nodes, \(\Delta t=0.00125\) and four steps. It stores the initial state plus four frames. At this short startup time there is no developed recirculating cavity to compare with a steady benchmark. The existing longer animation can be regenerated with:

python -m examples.navier_stokes_cavity --cells 16 --end 20 --backend cpp --output outputs/cavity.gif

Use --backend python without the C++ setup. All arithmetic in this example, including the global block solve, is Float64. Run time includes operator assembly; the final time 20 requires 16,000 steps at the fixed time step.

Diagnostic Meaning
linear_residual_max Maximum absolute residual of the last coupled solve
continuity_equation_max \(\|D_xu+D_yv+\lambda\boldsymbol1\|_\infty\); algebraic continuity-row residual
max_divergence \(\|D_xu+D_yv\|_\infty\) at pressure nodes; physical constraint defect
compatibility Signed last multiplier \(\lambda\)
pressure_mean Arithmetic mean of the final pressure unknowns
max_speed Maximum sampled velocity magnitude

The short run gives a linear residual around \(7.1\times10^{-14}\) and a continuity-row residual around \(1.4\times10^{-14}\) in the verified Float64 run. The recorded short-run divergence is about \(7.925\times10^{-4}\); the 16-cell \(t=20\) run has about \(0.0250\). Neither is roundoff-sized. The animation's smoothness is not an incompressibility or pressure-validation result. Display interpolation is separate from the RBF-FD solve.

8. Identify the reusable pieces

Mathematical ingredient Construction you can reuse
Different field locations source and targets in each operator map
Spatial differentiation The vv, vp, and pv operator collections
Nonlinear transport The explicit convection expression
Coupling and boundary equations The assembled sparse block matrix
Time integration The update loop and stored previous convection
Pressure reference The explicit arithmetic-mean constraint

These pieces belong to this algorithm. Changing one may require changing the others: for example, a new pressure boundary treatment cannot be introduced only by changing a plotting or reconstruction call. The divergence-free Stokes space in the preceding lesson uses a different construction.

9. Modify the algorithm deliberately

  • Change viscosity in solve to change Reynolds number; reassess the explicit convection time step. The Python function accepts dt directly.
  • Change the two spaces/stencil size in rbffd to test kernels and polynomial degrees.
  • Replace the convection expression to test another nonlinear discretization.
  • Change clouds and its boundary labels to try another geometry; rebuild all maps.
  • Inspect vv.dx.local(i) or vv.dx.reconstruct_local(i) before changing weights.
  • Compare velocity profiles, divergence, pressure and refinement separately. A smaller linear residual alone cannot establish that a flow solution is accurate.

For example, from a checkout:

from examples.navier_stokes_cavity import solve
points, times, velocities, diagnostics = solve(cells=6, dt=.000625, end=.005)
Complete maintained solver, including imports and diagnostics
"""A small Re=100 lid-driven cavity using staggered RBF-FD.

Run ``python -m examples.navier_stokes_cavity`` after installing
``rbflab[examples]``. The default Python backend needs no C++ build or mesher.
"""
from pathlib import Path
import argparse

import numpy as np
from scipy.sparse import bmat, csr_matrix, eye
from scipy.sparse.linalg import splu
import rbflab as r
from rbflab import viz


def clouds(cells):
    """Vertices carry pressure; triangle edge midpoints carry velocity."""
    pressure = r.geometry.unit_box_grid(cells)
    node = np.arange((cells + 1) ** 2).reshape(cells + 1, cells + 1)
    a, b = node[:-1, :-1].ravel(), node[1:, :-1].ravel()
    c, d = node[1:, 1:].ravel(), node[:-1, 1:].ravel()
    triangles = np.vstack((np.column_stack((a, b, c)),
                           np.column_stack((a, c, d))))
    edges = np.vstack((triangles[:, [0, 1]], triangles[:, [1, 2]],
                       triangles[:, [2, 0]]))
    edges = np.unique(np.sort(edges, axis=1), axis=0)
    points = pressure.points[edges].mean(axis=1)
    sides = (("left", 0, 0, -1), ("right", 0, 1, 1),
             ("bottom", 1, 0, -1), ("top", 1, 1, 1))
    boundary, normals = {}, {}
    for name, axis, value, sign in sides:
        ids = np.flatnonzero(np.isclose(points[:, axis], value))
        normal = np.zeros(2); normal[axis] = sign
        boundary[name] = ids
        normals[name] = np.tile(normal, (len(ids), 1))
    return r.PointCloud(points, boundary, normals), pressure


def solve(*, cells=16, dt=.00125, end=20., backend="python", frames=60):
    """Advance CN diffusion / AB2 convection with a coupled pressure constraint.

    All arrays and sparse operators use Float64. A compatibility multiplier
    allows a spatially constant divergence defect; this is reported explicitly.
    Returns velocity samples, not a pressure time history. See the cavity
    tutorial for the block equations and the meaning of each diagnostic.
    """
    if cells < 6 or dt <= 0 or end <= 0 or frames < 2:
        raise ValueError("Require cells >= 6 and positive dt, end, and frames >= 2")
    steps = round(end / dt)
    if not np.isclose(steps * dt, end, atol=1e-12, rtol=0):
        raise ValueError("end must be an integer multiple of dt")
    local = (r.PythonBackend() if backend == "python" else
             r.CppBackend(threads=8) if backend == "cpp" else None)
    if local is None:
        raise ValueError("backend must be 'python' or 'cpp'")
    velocity, pressure = clouds(cells)
    rbffd = r.RBFFD(spaces=r.MixedSpace({"u": r.ScalarSpace(r.PHS(7), 3),
                                         "p": r.PressureSpace(r.PHS(7), 3)}),
                    stencil_size=28, local_backend=local)
    differential = {"dx": r.Derivative(0), "dy": r.Derivative(1),
                    "lap": r.Laplacian()}
    def operators(source, target, space):
        return rbffd.operators(source=source, targets=target, space=space,
                               operators=differential)
    vv = operators(velocity, velocity, "u")
    vp = operators(velocity, pressure, "u")
    pv = operators(pressure, velocity, "p")
    dx, dy, lap = (vv[name].matrix for name in ("dx", "dy", "lap"))
    Dx, Dy = vp.dx.matrix, vp.dy.matrix
    Gx, Gy = pv.dx.matrix, pv.dy.matrix

    inside, wall = velocity.interior_indices, velocity.boundary_indices
    n, m = len(velocity.points), len(pressure.points)
    viscosity = .01  # Re = lid speed * box width / viscosity = 100
    # CN diffusion: A multiplies u^{n+1}, B multiplies u^n.
    A = eye(n, format="csr") / dt - .5 * viscosity * lap
    B = eye(n, format="csr") / dt + .5 * viscosity * lap
    a = A[inside][:, inside]
    zero = csr_matrix(a.shape)
    ones = csr_matrix(np.ones((m, 1)))
    # Unknowns: [u_I, v_I, pressure, compatibility multiplier].
    # Last row fixes the arithmetic pressure mean; the column of ones allows
    # D_x u + D_y v = -lambda at every pressure node, not exactly zero.
    coupled = bmat([[a, zero, Gx[inside], None],
                    [zero, a, Gy[inside], None],
                    [Dx[:, inside], Dy[:, inside], None, ones],
                    [None, None, ones.T, None]], format="csc")
    factor = splu(coupled)
    fixed = np.zeros((n, 2))
    fixed[velocity.boundary["top"], 0] = 1.
    # Eliminate the known velocity boundary values from momentum/continuity.
    correction = A[inside][:, wall] @ fixed[wall]
    continuity = -Dx[:, wall] @ fixed[wall, 0] - Dy[:, wall] @ fixed[wall, 1]
    u = fixed.copy()
    previous = None
    times, samples = [0.], [u.copy()]
    stride = max(1, steps // (frames - 1))
    for step in range(1, steps + 1):
        # Advective (not conservative/skew-symmetric) convection, evaluated at velocity nodes.
        convection = u[:, 0, None] * (dx @ u) + u[:, 1, None] * (dy @ u)
        explicit = convection if previous is None else 1.5 * convection - .5 * previous
        rhs = B[inside] @ u - explicit[inside] - correction
        # Reuse the same sparse LU because dt, viscosity and nodes are fixed.
        answer = factor.solve(np.r_[rhs[:, 0], rhs[:, 1], continuity, 0.])
        new = fixed.copy()
        new[inside, 0] = answer[:len(inside)]
        new[inside, 1] = answer[len(inside):2 * len(inside)]
        if not np.isfinite(new).all() or np.max(np.abs(new)) > 5:
            raise RuntimeError(f"Cavity solve became unstable at t={step * dt:g}")
        u, previous = new, convection
        if step % stride == 0 or step == steps:
            times.append(step * dt)
            samples.append(u.copy())
    divergence = Dx @ u[:, 0] + Dy @ u[:, 1]
    last_rhs = np.r_[rhs[:, 0], rhs[:, 1], continuity, 0.]
    diagnostics = {"velocity_nodes": n, "pressure_nodes": m,
                   "linear_residual_max": float(np.max(np.abs(coupled @ answer - last_rhs))),
                   "continuity_equation_max": float(np.max(np.abs(divergence + answer[-1]))),
                   "max_divergence": float(np.max(np.abs(divergence))),
                   "compatibility": float(answer[-1]),
                   "pressure_mean": float(np.mean(answer[2 * len(inside):2 * len(inside) + m])),
                   "max_speed": float(np.max(np.linalg.norm(u, axis=1)))}
    return velocity.points, np.asarray(times), np.asarray(samples), diagnostics


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cells", type=int, default=16)
    parser.add_argument("--end", type=float, default=20.)
    parser.add_argument("--backend", choices=("python", "cpp"), default="python")
    parser.add_argument("--output", type=Path,
                        default=Path("docs/assets/navier_stokes_cavity.gif"))
    args = parser.parse_args()
    points, times, velocities, diagnostics = solve(cells=args.cells,
                                                    end=args.end, backend=args.backend)
    viz.animate_velocity_samples(points, times, velocities, args.output,
                                 title="Lid-driven cavity  |  Re = 100",
                                 poster=args.output.with_suffix(".png"))
    print(f"Wrote {args.output} and {args.output.with_suffix('.png')}")
    print(diagnostics)


if __name__ == "__main__":
    main()

Download the solver. It uses public RBFLAB operators and ordinary SciPy sparse algebra; there is no hidden general-purpose Navier–Stokes solver behind this tutorial.