Skip to content

Equal-order flow in 3-D: the lid-driven cube

FEM cavity_3d_equal_order.py

A cube of fluid whose lid slides sideways: the lid-driven cavity in three dimensions. Equal-order P1/P1 elements with SUPG/PSPG stabilisation solve it, and the inf-sup stable Taylor–Hood pair checks the answer. In 3-D the equal-order pair matters: a P2 tetrahedron carries 10 nodes to P1's 4, so Taylor–Hood needs about five times the unknowns on the same mesh.

Speed in the 3-D lid-driven cavity at Re = 100 on two planes through the unit cube, in viridis from dark purple at rest to yellow under the lid, with white in-plane streamlines: on the plane y = 1/2 (left) one large clockwise vortex under the moving lid, on the plane z = 3/4 (right) the flow turning around in the horizontal plane.

The stabilised P1/P1 solution on a \(20^3\) cube: the speed on two planes, with in-plane streamlines. The lid moves in \(+x\), tapered to zero on its edges.

The problem

Steady incompressible Navier–Stokes at \(\mathrm{Re}=100\) in the unit cube:

\[(\mathbf u\!\cdot\!\nabla)\mathbf u - \nu\Delta\mathbf u + \nabla p = 0,\qquad \nabla\!\cdot\mathbf u = 0,\]

with the lid velocity \(u_x=16^2\,x^2(1-x)^2\,y^2(1-y)^2\) and no slip on the other walls. The stabilised form adds the momentum residual \(\mathbf r_m\), weighted by \(\tau\), to both equations:

\[\tau = \left(\mathbf u\cdot G\,\mathbf u + C_I\,\nu^2\,G\!:\!G\right)^{-1/2},\]

with \(G\) the cell metric tensor.

The jNO code

The formulation is the 2-D one with a longer coordinate list. d.cell_metric is a \(3\times3\) tensor here, and nothing in the stabilisation is dimension-specific:

G = d.cell_metric  # (3, 3) per quadrature point in 3-D: the symbol is dimension-generic
tau = jno.lag((dot(u, dot(G, u)) + C_I * nu**2 * ddot(G, G)) ** -0.5)
r_m = adv(u, u) - nu * jno.np.laplacian(u, [x, y, z]) + grad(p)  # the VECTOR Laplacian, in 3-D
momentum = momentum + tau * dot(adv(v, u), r_m)  # SUPG (+)
continuity = continuity - tau * dot(grad(q), r_m)  # PSPG (-)

The same function builds both discretisations, order=1, stabilised=True and order=2, stabilised=False, and \(\mathrm{Re}=100\) is reached by continuation in \(\nu\).

Result

On a structured \(6^3\) cube the vertical centre-line carries nodes of both velocity spaces, so the two solutions are compared without interpolation:

unknowns
stabilised P1/P1 1,372
Taylor–Hood P2/P1 6,934

The centre-line \(u_x\) of the two differs by at most 0.036, 3.3 % of the profile range, at a fifth of the unknowns.

Full script

The whole script, as it runs in the tests
"""**Equal-order flow in 3-D** -- where the stabilised pair actually pays for itself.

    (u.grad)u - nu lap u + grad p = 0,   div u = 0,   Re = U L / nu = 100

In 2-D, Taylor-Hood P2/P1 costs about 2.9x the unknowns of stabilised P1/P1. In 3-D the gap is wider,
because a P2 tetrahedron carries 10 nodes to P1's 4: about 5x on the same mesh. The head-to-head below
runs both pairs on a structured N = 6 cube.

This is the same formulation as the 2-D stabilised tutorial -- SUPG on momentum, PSPG on continuity,
`dom.cell_metric` for a direction-aware `tau` -- written for three dimensions by changing the
coordinate list and `value_shape`. Nothing else about it is 3-D-specific.

The mesh is **structured**, so the vertical centreline x = y = 0.5 carries nodes of both the P1 and
the P2 velocity space and the two solutions can be compared where they both live, with no
interpolation in the comparison itself.
"""

import jax

jax.config.update("jax_enable_x64", True)

import numpy as np

import jno

run = jno.setup(__file__)

N = 6  # structured n x n x n cube; both discretisations must fit a direct solve together
C_I = 36.0
RE_LADDER = [5.0, 10.0, 25.0, 50.0, 100.0]


def cavity3d(n=N, order=1, stabilised=True):
    d = jno.shape.box(0, 0, 0, 1, 1, 1).structured(n=n).domain()
    x, y, z = d.variable("interior", split=True)[:3]
    top = d.variable("top", split=True)[:3]
    walls = [d.variable(side, split=True)[:3] for side in ("bottom", "left", "right", "front", "back")]

    nu = jno.np.parameter((1,), name="nu")
    u = d.unknown.vector(3, order=order)
    p = d.unknown.scalar(name="p")
    v, q = u.test(), p.test()

    grad = lambda w: jno.np.jacobian(w, [x, y, z])
    div = lambda w: jno.np.trace(grad(w))
    dot, ddot = jno.np.inner, lambda a, b: jno.np.inner(a, b, n_contract=2)
    adv = lambda w, b: dot(grad(w), b)  # (b . grad) w

    momentum = dot(adv(u, u), v) + nu * ddot(grad(u), grad(v)) - p * div(v)
    continuity = -q * div(u)

    if stabilised:
        G = d.cell_metric  # (3, 3) per quadrature point in 3-D: the symbol is dimension-generic
        tau = jno.lag((dot(u, dot(G, u)) + C_I * nu**2 * ddot(G, G)) ** -0.5)
        r_m = adv(u, u) - nu * jno.np.laplacian(u, [x, y, z]) + grad(p)  # the VECTOR Laplacian, in 3-D
        momentum = momentum + tau * dot(adv(v, u), r_m)  # SUPG (+)
        continuity = continuity - tau * dot(grad(q), r_m)  # PSPG (-)

    # A lid driven in x, tapered to zero on all four top edges so the corners carry no singularity.
    lid = 16.0 * top[0] ** 2 * (1 - top[0]) ** 2 * 16.0 * top[1] ** 2 * (1 - top[1]) ** 2
    return d, jno.fem(
        [
            momentum,
            continuity,
            u(*top)[0] - lid,
            u(*top)[1] - 0.0,
            u(*top)[2] - 0.0,
            *[u(*w) - 0.0 for w in walls],
            p.pin(),
        ]
    )


def climb(fem):
    return np.asarray(
        fem.solve(
            nonlinear=jno.solve.newton(direct=True, rtol=1e-8, atol=1e-8),
            linear=jno.solve.lu(backend="host"),
            continuation=jno.solve.continuation(nu=[1.0 / r for r in RE_LADDER]),
        )
    )


def centreline(fem, sol, tol=1e-9):
    """`u_x` up the vertical centreline x = y = 0.5, at that field's own nodes."""
    pts = np.asarray(fem.points)
    uv = sol[fem.offsets[0] : fem.offsets[1]].reshape(len(pts), 3)
    on = (np.abs(pts[:, 0] - 0.5) < tol) & (np.abs(pts[:, 1] - 0.5) < tol)
    order = np.argsort(pts[on, 2])
    return pts[on, 2][order], uv[on, 0][order]


print(f"3-D lid-driven cavity, {N}x{N}x{N} structured tets, Re = {RE_LADDER[-1]:.0f}")

runs = {}
for label, order, stab in (("stabilised P1/P1", 1, True), ("Taylor-Hood P2/P1", 2, False)):
    d, fem = cavity3d(order=order, stabilised=stab)
    sol = climb(fem)
    runs[label] = (fem, sol)
    print(f"{label:<18}: {fem.dofs:6d} dofs")

fem_s, sol_s = runs["stabilised P1/P1"]
fem_t, sol_t = runs["Taylor-Hood P2/P1"]
print(f"\nTaylor-Hood costs {fem_t.dofs / fem_s.dofs:.1f}x the DOFs (a P2 tet carries 10 nodes to P1's 4)")

zs, ux_s = centreline(fem_s, sol_s)
zt, ux_t = centreline(fem_t, sol_t)
assert len(zs) > 3 and len(zt) > 3, "the centreline must carry nodes of both spaces"
ux_ref = np.interp(zs, zt, ux_t)  # sample the finer P2 profile at the P1 nodes
err = float(np.max(np.abs(ux_s - ux_ref)))
span = float(np.ptp(ux_ref))

print(f"\nCentreline u_x (x = y = 0.5), {len(zs)} P1 nodes vs {len(zt)} P2 nodes:")
print(f"  max deviation {err:.4f}  ({100 * err / span:.1f}% of the profile range {span:.4f})")
print(
    f"  extrema   equal-order {ux_s.min():+.4f} / {ux_s.max():+.4f}   Taylor-Hood {ux_ref.min():+.4f} / {ux_ref.max():+.4f}"
)

assert err < 0.15 * span, f"equal-order disagrees with the stable pair by {err:.3f} ({100 * err / span:.0f}%)"
print("\nEqual-order tracks the stable pair in 3-D, at a fifth of the degrees of freedom.")