Examples and tutorials » Partial differential equations » Solving the Navier–Stokes equations

Follow the development of a vortex in a lid-driven cavity.

The Stokes tutorial introduces velocity–pressure coupling without inertia. Here the same cavity starts from rest, the lid is set in motion, and convection transports momentum through the fluid. The exported time series is used to produce the animation below.

The mathematical problem

On $\Omega=(0,1)^2$ , the nondimensional incompressible equations are

\[ \partial_tu+(u\cdot\nabla)u-\nu\Delta u+\nabla p=0, \qquad \operatorname{div}u=0. \]

Initially $u=0$ . The bottom and side walls are stationary. On the top,

\[ u(x,1,t)=\bigl(U_{\mathrm{lid}}r(t)[1-((x-c(t))/w)^2]_+^2,0\bigr), \qquad r(t)=\min(t,1), \]

where $U_{\mathrm{lid}}=2$ , $[a]_+=\max(a,0)$ , $w=0.25$ , and

\[ c(t)=0.5-0.22\cos(2\pi t/8). \]

The smooth driving patch travels horizontally between $x=0.28$ and $x=0.72$ , completing one round trip in eight time units. Its support stays away from the side walls, and its velocity points to the right even when the patch itself travels left. The amplitude ramps over one time unit. Its peak speed after the ramp is two and the cavity width is one. With $\nu=0.01$ , the Reynolds number based on those scales is $\mathrm{Re}=200$ .

The compact lid profile vanishes at the corners, avoiding the conflicting corner values of a constant-speed lid. Comparisons with classical cavity reference data would require matching that boundary profile as well as the Reynolds number. Pressure is normalized by $\int_\Omega p\,dx=0$ .

The time discretization

One Oseen solve is performed per time step. The transport velocity is taken from the previous step, while the transported velocity is implicit. With $\Delta t=0.01$ ,

\[ \frac{u^{n+1}-u^n}{\Delta t} +(u^n\cdot\nabla)u^{n+1}-\nu\Delta u^{n+1}+\nabla p^{n+1}=0, \qquad \operatorname{div}u^{n+1}=0. \]

The method is first order in time and uses a semi-implicit Oseen linearization. The 2,000 steps reach $t=20$ . The resulting transient can be assessed through time-step and mesh refinement.

Multiplication by test velocity $v$ gives the momentum equation

\[ \frac{1}{\Delta t}\int_\Omega u^{n+1}\cdot v\,dx +\int_\Omega\bigl((u^n\cdot\nabla)u^{n+1}\bigr)\cdot v\,dx +\nu\int_\Omega\nabla u^{n+1}:\nabla v\,dx -\int_\Omega p^{n+1}\operatorname{div}v\,dx =\frac{1}{\Delta t}\int_\Omega u^n\cdot v\,dx. \]

Continuity and the pressure-mean multiplier are imposed as in the Stokes example. Time-step and mesh refinement are needed to assess temporal and spatial error separately.

1. Prepare the cavity

The unit square is refined to 2,048 triangles (33 by 33 mesh vertices), retaining the Stokes example's boundary labels. Quadratic velocity and linear pressure give 9,539 velocity and pressure DOFs, plus one pressure-mean multiplier.

  constexpr size_t nodes = 33;
  constexpr Attribute lid = 2;
  constexpr Attribute walls = 3;
  constexpr Real boundaryTolerance = 1e-12; // Coordinate tolerance on this unit grid.
  Mesh mesh = Mesh().UniformGrid(Polytope::Type::Triangle, {nodes, nodes});
  mesh.scale(1.0 / (nodes - 1));
  mesh.getConnectivity().compute(1, 2);
  for (auto edge = mesh.getFace(); !edge.end(); ++edge)
  {
    if (!edge->isBoundary())
      continue;
    bool onTop = true;
    for (auto vertex = edge->getVertex(); !vertex.end(); ++vertex)
      onTop = onTop && std::abs(vertex->getCoordinates().y() - 1) < boundaryTolerance;
    mesh.setAttribute({1, edge->getIndex()}, onTop ? lid : walls);
  }

2. Initialize fields and output

The Taylor–Hood pair uses quadratic velocity and linear pressure. The stored velocity holds the previous time step during assembly; after a successful solve, it is replaced with the new solution. The XDMF time series starts with the fluid at rest. A snapshot is exported every five time steps, giving a visualization interval of $0.05$ without enlarging the solver time step.

  H1 velocitySpace(std::integral_constant<size_t, 2>{}, mesh, 2);
  H1 pressureSpace(std::integral_constant<size_t, 1>{}, mesh);
  P0g meanSpace(mesh);
  TrialFunction u(velocitySpace);
  TrialFunction p(pressureSpace);
  TrialFunction multiplier(meanSpace);
  TestFunction v(velocitySpace);
  TestFunction q(pressureSpace);
  TestFunction meanTest(meanSpace);
  constexpr Real peakLidSpeed = 2; // Doubled driving speed for the stronger transient.
  constexpr Real viscosity = 0.01; // Reynolds number 200 for unit cavity width.
  constexpr Real dt = 0.01;
  constexpr size_t steps = 2000; // Final time 20, for the transient demonstration.
  constexpr size_t outputEvery = 5; // Export every 0.05 time units for visualization.
  constexpr Real rampTime = 1; // Ramp the lid over one simulation time unit.
  constexpr Real travelAmplitude = 0.22; // Center travels between x=0.28 and x=0.72.
  constexpr Real travelPeriod = 8; // One horizontal round trip in simulation time.
  constexpr Real halfWidth = 0.25; // Compact support stays clear of both corners.
  const Real pi = Math::Constants::pi();
  GridFunction velocity(velocitySpace);
  GridFunction pressure(pressureSpace);
  velocity = Zero(2);
  pressure = 0.0;
  IO::XDMF xdmf("NavierStokes");
  xdmf.grid().setMesh(mesh).add("velocity", velocity).add("pressure", pressure);
  xdmf.write(0).flush();

3. Advance one step at a time

Mult(Jacobian(u), velocity) expresses $(u^n\cdot\nabla)u^{n+1}$ . The convection term makes the linear system nonsymmetric and is solved with sparse LU. Each time step checks solver success before updating or writing the fields.

  for (size_t step = 1; step <= steps; ++step)
  {
    const Real time = step * dt;
    const Real ramp = std::min<Real>(1, time / rampTime);
    const Real center = 0.5 - travelAmplitude * std::cos(2 * pi * time / travelPeriod);
    RealFunction lidSpeed = [=](const Point& point) {
      const Real offset = (point.x() - center) / halfWidth;
      const Real profile = std::max<Real>(0, 1 - offset * offset);
      return peakLidSpeed * ramp * profile * profile;
    };
    VectorFunction lidVelocity{lidSpeed, Zero()};
    Problem flow(u, p, multiplier, v, q, meanTest);
    flow = (1 / dt) * Integral(u, v) + Integral(Dot(Mult(Jacobian(u), velocity), v)) +
      viscosity * Integral(Jacobian(u), Jacobian(v)) - Integral(p, Div(v)) +
      Integral(Div(u), q) + Integral(multiplier, q) + Integral(p, meanTest) -
      (1 / dt) * Integral(velocity, v) + DirichletBC(u, lidVelocity).on(lid) +
      DirichletBC(u, Zero(2)).on(walls);
    Solver::SparseLU solver(flow);
    solver.solve();
    if (!solver.success())
      return EXIT_FAILURE;
    velocity.setData(u.getSolution().getData());
    pressure.setData(p.getSolution().getData());
    if (step % outputEvery == 0)
      xdmf.write(time).flush();
    std::cout << "Step " << step << " / " << steps << ", time " << time << ", lid center "
              << center << std::endl;
  }

Each iteration assembles the Oseen form using the previous velocity and current lid data, solves the resulting linear system, and updates the stored fields.

4. Flow visualization

Computed speed and instantaneous streamlines from rest to time 20. The cyan trace follows the computed top-wall speed as the driving patch travels horizontally. The displayed time is simulation time.

The right panel shows instantaneous streamlines integrated by ParaView through each exported velocity field. Their evolution displays the displacement of the primary recirculation as the driving patch travels along the lid.

Open NavierStokes.xdmf in ParaView and select Apply. Color by the magnitude of velocity, then use the time controls to inspect the evolution. Add the Stream Tracer filter to examine circulation and color by pressure to inspect the pressure field. Keep all referenced HDF5 snapshots next to the XDMF file.

The examples/PDEs/visualize_paraview.py script uses ParaView to produce transparent PNG frames, then FFmpeg encodes the WebM from the same time series. A still image of the final frame is also available.

Image
Computed speed at time 20 with moving lid forcing.
Image
Instantaneous circulation and velocity directions at time 20.

Complete program

See NavierStokes.cpp for this native example. A separate PETSc SNES example demonstrates a fully implicit nonlinear formulation with both Newton convection terms. Its time integrator and nonlinear solve differ from the Oseen scheme presented here; see the PETSc guide for that backend.