Programming Homework 01

Submission Deadline: 29.04.2026 - 23:55
  • Your homework solution has to be handed in as a group solution via Moodle.
  • Your notebooks must run without errors in our environment on the RWTH-Cluster. See here for more information on how to get started.
Participant list

Please add your names and student ID (Matrikelnummer) here:

  1. Name, ID
  2. Name, ID
  3. Name, ID
  4. Name, ID
Before you start

Make sure that you update the library folder in your CMM directory. Download link: library.tar.gz

Make sure that you update your dolfinx_latest.sif container image.

You can use the following command on the RWTH cluster/Linux:

    wget https://mbd.pages.rwth-aachen.de/courses/cmm/content/exercises/notebooks/homework01.out.ipynb
    rm -rf library library.tar.gz || true
    wget https://mbd.pages.rwth-aachen.de/courses/cmm/content/exercises/notebooks/library.tar.gz
    tar -xvzf library.tar.gz
    rm library.tar.gz
    rm dolfinx_latest.sif
    apptainer pull oras://registry.git.rwth-aachen.de/mbd/courses/containers/dolfinx:latest

Learning goals

  • Derive a weak formulation for a scalar advective PDE
  • Understand the basics of the Discontinuous Galerkin (DG) method
  • Compare DG(0) and the DG(1) method for scalar advection
  • Learn to weakly enforce boundary conditions in a DG context
  • Learn to visualize Streamlines and Pathlines in ParaView

TODOs:

Make sure that all tests in the notebook run without errors. The following tasks need to be completed:

Unsteady Advection Equation

In the lecture, we learned about the local form of a generic transport equation

\[ \begin{aligned} \partial_t \Psi + \nabla \cdot \left( \Psi \mathbf v \right) &= \nabla \cdot \left( \mathbf{D} \nabla \Psi \right) + S \end{aligned} \]

where \(\Psi\) is our transported quantity, e.g. density, height of a water wave, temperature, momentum or energy. \(\mathbf{v}\) is the convective transport velocity, \(\mathbf{D}\) is the diffusion coefficient (it can be a scalar or a tensor) and \(S\) is the production or decay of the transported quantity.

Previously in ‘My first FenicsX program’, we learned about the weak formulation of the diffusive term for a steady state problem along with with its approximate numerical solution using the FEM.

In this tutorial, we will focus on unsteady convective transport problem and solve it using the Discontinuous Galerkin (DG) method.

By considering a scalar quantity \(\Psi=q\) and neglecting the non-convective(diffusive) and production/decay terms in local form of the generic transport equation, we arrive at the scalar advection PDE

\[ \partial_t q + \nabla \cdot \left( q \mathbf v \right) = 0 \quad q \in \Omega \]

and apply the following boundary conditions

\[ \left. \nabla q \cdot \mathbf{n}\right|_{\partial\Omega} = 0. \]

Here, \(q \in \mathbb{R}\) is the unknown of the system, \(\mathbf{v}(t,x)= (2,1)^T \in \mathbb{R}^2\) is a given advection velocity field within the domain \(\Omega = [0, 3] \times [0, 3] \in \mathbb{R}^2\) and its boundary \(\partial\Omega\).

A primer on the Discontinuous Galerkin Method

We want to approximate our unknown \(q \in V=DG(1)\), where \(DG(1)\) are Legendre polynomials of first order. Note that \(DG(1)\) and \(CG(1)\) can both be Legendre polynomials of first order. However, in \(DG(1)\) the basis functions are not required to be continuous across cell interfaces (facets). Hence the name of discontinuous and continuous Galerkin elements. This has two immediate implications:

  1. We need two degrees of freedom (dof) for each vertex/node in the inner part of our domain. This increases the storage demand of DG compared to a CG-FEM formulation.
  2. Accounting for these jumps (two function values at one physical location) introduces new terms in our weak formulation

An illustration of DG(0), DG(1) and CG(1) is shown below:

fig = library.plot.DG_illustration()

In contrast to the usual weak form derivation in CG-FEM, where we multiply the PDE with a test function \(\phi \in V\) over the whole domain \(\Omega\), we want to start our derivation for a single element e in our mesh. This is only for didactic reasons and will result in the identical weak form, as if we start with the integration over the full domain. To arrive at the weak form, we

  1. mutiply the PDE with a test function \(\phi^e \in V=DG(1)\) and integrate over the domain \(\Omega^e\), the domain where the basis function \(\phi^e\) is non-zero and perform integration by parts with the goal to rewrite the advective term in divergence form. Note that \(\phi^e\) indicates the basis on one element of the mesh only.
  2. use the divergence theorem to transform the domain (evolume) integral into a facet (surface) integral.
  3. introduce the concept of a numerical flux to resolve the ambiguity of the value of \(q\) on the facet between two elements.
  4. separate internal and boundary facets. The boundary conditions on the boundary facets will be weakly enforced in the numerical flux.
  5. sum over all elements to recover the integral over the entire domain \(\int_\Omega \cdot \, dx = \sum_e \int_{\Omega^e} \cdot \, dx\)
  6. Rewrite the resulting weak form by considering implementation details for FEniCSx.

Step 1 - Integration by parts

We start by mutiplying the PDE with a test function \(\phi^e \in V=DG(1)\) and integrate over the domain \(\Omega^e.\)

\[ \int_{\Omega^e} \partial_t q \phi^e \, dx +\int_{\Omega^e} \nabla \cdot \left( q \mathbf v \right) \phi^e \, dx = 0 \]

Performing integration by parts gives

\[ \Leftrightarrow \int_{\Omega^e} \partial_t q \phi^e \, dx + \int_{\Omega^e} \nabla \cdot \left( q \mathbf v \phi^e \right) \, dx - \int_{\Omega^e} \nabla \phi^e \cdot \left( q \mathbf v \right) \, dx= 0 \\ \]

The term \(\nabla \phi^e \cdot \left( q \mathbf v \right)\) is a jump term which we need to account for in our weak formulation. Later we will see how this term can be interpreted.

Step 2 - Divergence theorem

We then apply the divergence theorem to the convective term

\[ \begin{aligned} \int_{\Omega^e} \partial_t q \phi^e \, dx + \int_{\partial\Omega^e} \left( q \mathbf v \phi^e \cdot \mathbf{n}^e \right) ds - \int_{\Omega^e} \nabla \phi^e \cdot \left( q \mathbf v \right) \, dx= 0 \end{aligned} \]

Here, we obtain an integral over the boundaries of our element \(\partial\Omega^e\) and the outward pointing normal vector \(\mathbf{n}^e\) of the element. Now look image of the 1D representation of the DG(1) element above and note that there are two different types of facets:

  • interior facets: facets between two elements
  • boundary facets: facets between an element and the domain boundary

This is different to the CG-FEM formulation, where we only had a boundary integral over the domain boundary.

It is now important to realize that in \(\int_{\partial\Omega^e} \left( q \mathbf v \phi^e \cdot \mathbf{n}^e \right) ds\) the value \(q\) is not unique on the facet \(f\). It has two values, one on the element e that we are currently looking at and another value at its neighboring element. We will now denote \(q|_{f^e} = q^{+}\) and \(q|_{f^{\mathrm{neighbor}}} = q^{-}\). Similarly, we denote \(n^e = n^+\).

Step 3 - Numerical flux

It is still unclear which value we should assign to \(q^n\) on the facet. However, a solution can be borrowed the Finite Volume Method (FVM), as this method is build around discontinuous solutions at the facets. Without going into any details, the idea is to replace the flux \(F :=q \mathbf v \cdot \mathbf{n}^e\) in the integral \(\int_{\partial\Omega^e} \left( q \mathbf v \phi^e \cdot \mathbf{n}^e \right) ds\) with a numerical flux \(F^{\mathrm{num}}\). Typical choices for this numerical flux are the upwind and the Lax-Friedrichs flux. We will focus on the latter which is defined as

\[ F^{\mathrm{num}} = \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \]

where \(\left| \lambda \right|_{\mathrm{max}}\) is the maximal eigenvalue of the Jacobian of the flux function. In our case \(\left| \lambda \right|_{\mathrm{max}} = \left| \mathbf{v} \cdot \mathbf{n}^+ \right|\).

Step 4 - Boundary conditions

Inserting the numerical flux into our weak form, we now also want to differentiate between boundary facets, denoted as \(\int_{\partial\Omega^e_{bnd}} \cdot \, ds\) and interior facets \(\int{\partial_{\Omega^e_{int}}} \cdot \, dS\). We can hence write the weak form as

\[ \begin{aligned} & \int_{\Omega^e} \partial_t q \phi^e \, dx - \int_{\Omega^e} \nabla \phi^e \cdot \left( q \mathbf v \right) \, dx \\ & + \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) dS \\ & + \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) ds= 0 \end{aligned} \]

Weak enforcement of boundary conditions means that we do not alter the PDE or linear system in order to guarantee a certain boundary value. We rather build in the boundary condition in our weak formulation. In our case, we can simply prescribe the value in the \(q^{-}\) in the boundary integral \(\int_{\partial\Omega^e_{bnd}} \cdot dS\). To realize the extrapolation or outflow boundary condition \(\nabla q \cdot \mathbf{n} = 0 \quad \text{on } \partial\Omega\), we simply copy the value from the interior side of the facet to the exterior side, since a constant across the interface results in a zero gradient.

Instead of simplifying our weak form for our particular boundary condition, we only replace \(q^{-}\) with \(q^{G}\) in the boundary integral. \(q^{G}\) denotes the ghost cell value on the exterior side of the boundary facet and can also be used to model inflow or Dirichlet boundary conditions.

The weak form now reads

\[ \begin{aligned} & \int_{\Omega^e} \partial_t q \phi^e \, dx - \int_{\Omega^e} \nabla \phi^e \cdot \left( q \mathbf v \right) \, dx \\ & + \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) dS \\ & + \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{G} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{G} - q^{+}) \right] \phi^+ \right) ds= 0 \end{aligned} \]

Step 5 - Global integration

Now it is finally time to assemble the complete form by integrating over all elements \(\int_\Omega \cdot \, dx = \sum_e \int_{\Omega^e} \cdot \, dx\). The important realization is here that the interior facets appear twice, since the facet is shared by two elements. However, the boundary facets only appear once. So the integral over all facets can be written as \(\int_{\partial\Omega} \cdot \, ds = \sum_{e \in \Omega} \sum_{f \in e} \int_{\partial\Omega^f} \cdot \, ds\) where \(f \in e\) denotes the facets \(f\) in element \(e\).

Let’s make this more explicit by looking at the following figure. The left element in \(x \in [0, 1]\) has one boundary facet at \(x=0\) and an internal facet at \(x=1\). The right element in \(x \in [1, 2]\) has one internal facet at \(x=1\) and one boundary facet at \(x=2\). So we have one contribution for each boundary and two condtributions for the internal facet at \(x=1\).

fig = library.plot.DG_facet_integral_illustration()

We now want to replace the sum of all faces for each element \(\sum_{e \in \Omega} \sum_{f \in e}\) with a sum over all faces \(\sum_{f \in \Omega} = \sum_f\), therefore only looping over each facet once. This results in two contributions for each facet, as we need to add the contributions of the \(+\) and \(-\) side.

\[ \begin{aligned} & \sum_e \int_{\Omega^e} \partial_t q \phi^e \, dx - \sum_e \int_{\Omega^e} \nabla \phi^e \cdot \left( q \mathbf v \right) \, dx \\ & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) dS \\ & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{-} + q^{+} \right) \mathbf{v} \cdot \mathbf{n}^- - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{+} - q^{-}) \right] \phi^- \right) dS \\ & + \sum_f \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{G} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{G} - q^{+}) \right] \phi^+ \right) ds= 0 \end{aligned} \]

The final step is to realize that \(n^+ = - n^-\), which allows us to rearrange term with the intent two combine the two contributions from the numerical flux into one expression.

\[ \begin{aligned} & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) dS \\ & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{-} + q^{+} \right) \mathbf{v} \cdot \mathbf{n}^- - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{+} - q^{-}) \right] \phi^- \right) dS \\ \Leftrightarrow & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) dS \\ & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot (-1)\mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (-1)(q^{-} - q^{+}) \right] \phi^- \right) dS \\ \Leftrightarrow & + \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^+ \right) dS \\ & - \sum_f \int_{\partial\Omega^e_{int}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \phi^- \right) dS \\ \Leftrightarrow & \sum_f \int_{\partial\Omega^e_{int}} \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \underbrace{\left[ \phi^+ - \phi^- \right]}_{\text{jump of $\phi$}} dS \\ \end{aligned} \]

So the weak formulation reads

\[ \begin{aligned} & \sum_e \int_{\Omega^e} \partial_t q \phi^e \, dx - \sum_e \int_{\Omega^e} \nabla \phi^e \cdot \left( q \mathbf v \right) \, dx \\ & \sum_f \int_{\partial\Omega^e_{int}} \left[ \frac{1}{2} \left( q^{+} + q^{-} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{-} - q^{+}) \right] \underbrace{\left[ \phi^+ - \phi^- \right]}_{\text{jump of $\phi$}} dS \\ & + \sum_f \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{G} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{G} - q^{+}) \right] \phi^+ \right) ds= 0 \end{aligned} \]

Step 6 - Domain boundary integral in FEniCSx

The last step is an implementation detail of FEniCSx. In FEniCSx, the integral over the domain \(\int_{\partial\Omega^e_{bnd}} \cdot \, ds\) does not allow the \((q^{-}, q^{+})\) syntax, as there is no ambiguity at the outer boundaries. In the dof, there is only one value, namely the interior value \(q^{+}\). Therefore FEniCSx rewrites the integral with \(q^{+} \rightarrow q\) such that

\[ \begin{aligned} & \sum_f \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q^{+} + q^{G} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{G} - q^{+}) \right] \phi^+ \right) ds= 0 \\ \rightarrow & \sum_f \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q + q^{G} \right) \mathbf{v} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{\mathrm{max}} \right) (q^{G} - q) \right] \phi^+ \right) ds= 0 \end{aligned} \]

Time Discretization

Finally, in order to approximate the time derivative in the weak form we use the explicit Euler time stepping scheme given by

\[ \begin{aligned} &\sum_e \int_{\Omega^e} \partial_t q \phi^e \, dx + A(q^{+}, q^{G}, q, \mathbf{v}, {\phi^e}) \\ &= \sum_e \int_{\Omega^e} \left(\frac{q^{n+1} - q^n}{\Delta t} \right) {\phi^e} \, dx + A(q^{n, +}, q^{n, G}, q^{n}, \mathbf{v}^{n}, {\phi^e}) \end{aligned} \] where the function \(A\) represents the terms in the weak form without a time derivative.

When using the explicit Euler scheme, we have a stability restriction on the time step size. This criterion is called the Courant-Friedrichs-Lewy number, or CFL number. In our case, the CFL restriction reads

\[ \mathrm{CFL} = 1/(2 *\text{polynomial degree}+1)/\text{physical dimension} \]

and

\[ \Delta t = \frac{\mathrm{CFL} * l_{\mathrm{characteristic}}}{ \left( 2 \, |\lambda|_{\mathrm{max}} \right)} \]

with the characteristic length \(l_{\mathrm{characteristic}}=\min(dx, dy)\).

Note

If we replace \(n \rightarrow {n+1}\) in \(A\), it will result in time discretization with implicit Euler scheme.

Final Weak Form

After all this effort and mathematical manipulation, our weak form for the scalar advection equation reads

\[ \begin{aligned} & \sum_e \int_{\Omega^e} \left(\frac{q^{n+1} - q^n}{\Delta t} \right) \phi^e \, dx - \sum_e \int_{\Omega^e} \nabla \phi^e \cdot \left( q^{n} \mathbf{v}^{n} \right) \, dx \\ & \sum_f \int_{\partial\Omega^e_{int}} \left[ \frac{1}{2} \left( q^{n, +} + q^{n, -} \right) \mathbf{v}^{n} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{max} \right) (q^{n, -} - q^{n, +}) \right] \underbrace{\left[ \phi^+ - \phi^- \right]}_{\text{jump of $\phi$}} dS \\ & \sum_f \int_{\partial\Omega^e_{bnd}} \left( \left[ \frac{1}{2} \left( q^{n} + q^{n, G} \right) \mathbf{v}^{n} \cdot \mathbf{n}^+ - \frac{1}{2} \left( \left| \lambda \right|_{max} \right) (q^{n, G} - q^{n}) \right] \phi^+ \right) ds= 0 \end{aligned} \]

which is exactly the form that we will implement in FEniCSx.

Solving Scalar Advection with FEniCSx

We now proceed with solving the derived weak form of the scalar advection equation with a constant advection velocity \(\mathbf{v} = (2.0, 1.0)^{T}\) using FEniCSx. Here, we follow the steps similar to those in ‘My first FEniCSx program’.

Our goal is to approximate and observe the advection of a passive tracer (concentration) through the domain \(\Omega = [0, 3] \times [0, 3] \in \mathbb{R}^2\) and compare the solution obtained for both \(DG(0)\) and \(DG(1)\).

The intial concentration of the passive tracer to is given by

\[ q = \begin{cases} 2.0 & r \leq R \\ 1.0 & r > R \\ \end{cases} \]

where \(r = \sqrt{(x-0.7)^2 + (y-0.7)^2}\) and \(R = 0.15\)

Let’s go!

First, we import some of the necessary python libraries

Note

Make sure to download and unpack the library.tar.gz file in the same directory as this notebook.

import os
from mpi4py import MPI
import numpy as np
import dolfinx
from dolfinx import fem
import basix
import tqdm
from petsc4py import PETSc
import numpy as np
import ufl
import pyvista
from  dolfinx.fem import petsc
from IPython.display import Image, display

CMM_DIR = os.getcwd()
os.environ["PYTHONPATH"] = f"{CMM_DIR}:{os.environ.get('PYTHONPATH', '')}"

import library.plot

import library.helpers
import library.limiter

output_dir = library.helpers.make_unique_dir(os.path.join(CMM_DIR, 'ex01'))

if os.getenv('DEVCONTAINER'):
    pyvista.start_xvfb()

1. Mesh and computational domain

First we define and discretize our discrete computational domain \(\Omega = [0, 3] \times [0, 3] \in \mathbb{R}^2\)

from dolfinx import mesh

number_elements_x = 100
number_elements_y = 100
P0 = [0, 0]
P1 = [3, 3]
domain = mesh.create_rectangle(
    MPI.COMM_WORLD, [P0, P1],
    [number_elements_x, number_elements_y], 
    cell_type=mesh.CellType.quadrilateral
)

2. Our first discontinuous Galerkin elements

We now define a function, that will help us create function spaces for the scalar quantity \(q\) to compare \(DG(0)\) and \(DG(1)\). Additionally the it also creates for us a function space for the advection velocity field \(\mathbf{v}\), which is later used for visualization.

def generate_functionspaces(domain):
    mesh_element_name = domain.topology.cell_name()  
    """ type of mesh basix.ufl.element, e.g. "quadrilateral" """


    elem_DG0 = basix.ufl.element("DG", domain.topology.cell_name(), 0)
    space_DG0 = fem.functionspace(domain, elem_DG0)

    elem_DG1 = basix.ufl.element("DG", domain.topology.cell_name(), 1)
    space_DG1= fem.functionspace(domain, elem_DG1)
    
    elem_Vel = basix.ufl.element("DG", domain.topology.cell_name(), 1, 
                                 shape=(domain.geometry.dim,))
    space_Vel = fem.functionspace(domain, elem_Vel)
    
    return space_DG0, space_DG1, space_Vel

3. The weak form and UFL: From Math to Code

In the following function, we implement the weak form for our scalar advection equation. This requires us to also

  • define the advection velocity
  • identify the facet normals
  • differentiate between integration measures for the interior and boundary facets
  • compute CFL number , \(|\lambda|_{\mathrm{max}}\) and characteristic length to estimate the time step size
  • define the numerical Lax-Friedrichs flux function
def weak_form_advection(functionspace, q_n, q_np, t, x):

    # constant advection velocity 
    a = ufl.as_vector((2.0, 1.0))

    # facet normals
    n = ufl.FacetNormal(domain)
    
    # integration measures domain, internal and boundary facets
    dx = ufl.dx
    dS = ufl.Measure("dS", domain=domain)
    facet_tags = library.helpers.generate_facets_tags(domain, P0, P1)
    ds = ufl.Measure("ds", domain=domain, subdomain_data=facet_tags)

    # time step size estimation
    basis_function_degree = functionspace.ufl_element().degree
    N = number_elements_x * number_elements_y
    dim = 2
    CFL = 1/(2*basis_function_degree+1)/dim

    # computing the maximum eigen value of the jacobian of flux
    max_abs_a = abs(np.array(a, dtype=float)).max()
    
    characteristic_length = 1/max(number_elements_x, number_elements_y)
    _dt = CFL *characteristic_length / max_abs_a / 2 
    dt = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(_dt))

    q = q_n
    q_extrapolation = q_n

    test_q = ufl.TestFunction(functionspace)
    trial_q = ufl.TrialFunction(functionspace)

    # numerical Lax-Friedrichs flux
    propagation_speed = ufl.dot(a, n("+"))
    propagation_speed_bnd = ufl.dot(a, n)

    numerical_flux = lambda qp, qm, a, n , propagation_speed: (
        ufl.dot(0.5 * (a*qp + a*qm), n)
            - 0.5 * propagation_speed * (qm - qp)
        )

    # weak formulation
    weak_form =  test_q * (trial_q-q)/dt * dx
    weak_form += - ufl.dot(ufl.nabla_grad(test_q), (a * q)) * dx
    weak_form += ufl.dot(
        (test_q("+") - test_q("-")), 
        numerical_flux(q("+"), q("-"), a, n("+"), propagation_speed)
        ) * dS
    weak_form += ufl.dot(
        (test_q),
        numerical_flux(q, q_extrapolation, a, n, propagation_speed_bnd)
        ) * (ds(1) + ds(2) + ds(3) + ds(4))
    
    weak_form_lhs = fem.form(ufl.lhs(weak_form))
    weak_form_rhs = fem.form(ufl.rhs(weak_form))

    return weak_form_lhs, weak_form_rhs, dt

4. Boundary and Initial Conditions

The scalar advection equation is an initial-boundary-value problem (IBVP). Hence we require both boundary and initial conditions.

The boundary conditions are already weakly enforced through the weak form. So we now only need to define the initial condition for our problem

def ic_q(x):
    R = 0.15
    r = np.sqrt((x[0] - 0.7)**2 + (x[1] - 0.7)**2)
    return np.where(r <= R, 2., 1.)

5. Assemble and solve the linear system

First we define a function that allocates memory and updates options for the solver

def prepare_solver(weak_form_lhs, weak_form_rhs):

    A = petsc.create_matrix(weak_form_lhs)
    b = petsc.create_vector(weak_form_rhs)

    solver = PETSc.KSP().create(domain.comm)
    solver.setOperators(A)
    solver.setType(PETSc.KSP.Type.BCGS)
    preconditioner = solver.getPC()
    preconditioner.setType(PETSc.PC.Type.JACOBI)
    return solver, A, b

Then we need to define our time-stepping loop where we solve for and write the solution to disk at each time step.

Note

We use a flux limiter in the time-stepping loop, which removes spurious osscillations for advective problems when solved with higher order methods. For \(DG(0)\), no limiter is necessary. The details of limiters are beyond the scope of this class. However, we need to be aware that any polynomial degree > 0 might lead to problems when not addressed properly.

def solve_time_loop(
        name: str, 
        weak_form_function, functionspace, initial_condition, 
        end_time, 
        output_path, 
        space_plot_vel, expr_vel, 
        limiter=False):
        
    t = fem.Constant(domain, dolfinx.default_scalar_type(0.0))    
    x = ufl.SpatialCoordinate(domain)
        
    q_n = fem.Function(functionspace, name=r'$q^n$')
    q_np1 = fem.Function(functionspace, name=r'$q^{n+1}$')
    weak_form_lhs, weak_form_rhs, dt = weak_form_function(
        functionspace, 
        q_n, 
        q_np1, 
        t, x
        )
    
    solver, A, b = prepare_solver(weak_form_lhs, weak_form_rhs)    
    
    # Initial conditions
    q_n.interpolate(initial_condition)
    q_np1.interpolate(initial_condition)

    num_timesteps = int(end_time/dt.value)
    
    # VTK writer
    os.makedirs(output_path, exist_ok=True)
    vtk_file_abs_path_name = os.path.join(output_path, f"{name}.pvd")
    vtk_writer = dolfinx.io.VTKFile(
        domain.comm, vtk_file_abs_path_name, "w+"
    )
    # We only need the following for plotting of the velocity as a vector field
    velocity_field = fem.Function(space_plot_vel, name=r'$vel$')
    velocity_field.interpolate(expr_vel(float(t.value)))
    
    vtk_writer.write_function([q_np1, velocity_field], t=0.0)
    n_snapshots = 30
    timeline_snapshots = np.linspace(0, num_timesteps, n_snapshots, dtype=int)

    progress = tqdm.tqdm(
        desc="Setup " + name + ", solving PDE", total=num_timesteps
        )
    if limiter:
        limiter = library.limiter.VertexBasedLimiter(functionspace, alpha=0.0)

    for i in range(num_timesteps):
        progress.update(1)
        q_n.interpolate(q_np1)

        A.zeroEntries()
        petsc.assemble_matrix(A,weak_form_lhs)
        A.assemble()
        with b.localForm() as loc:
            loc.set(0)
        petsc.assemble_vector(b,weak_form_rhs)

        b.ghostUpdate(
            addv=PETSc.InsertMode.ADD_VALUES, 
            mode=PETSc.ScatterMode.REVERSE
            )
        solver.solve(b, q_np1.x.petsc_vec)
        if limiter:
            limiter.apply(q_np1)

        q_np1.x.scatter_forward()
        t.value += dt.value
        
        if i in timeline_snapshots:
            velocity_field.interpolate(expr_vel(float(t.value)))
            vtk_writer.write_function([q_np1, velocity_field], t=t.value)

    progress.close()
    return q_np1

6. Visualization: Comparing DG(0) and DG(1)

We now proceed by generating our \(DG(0)\) and \(DG(1)\) function spaces and use them along with our functions for the weak form, and initial conditions to solve the scalar advection equation and compare the results for \(DG(0)\) and \(DG(1)\).

space_DG0, space_DG1, space_Vel = generate_functionspaces(domain)
expr_vel = lambda t: lambda x: np.stack(
    (2.0 * np.ones(x.shape[1]), 1.0 * np.ones(x.shape[1]))
    )
q_DG0 = solve_time_loop(
    name="advection DG(0)",
    weak_form_function=weak_form_advection, 
    functionspace=space_DG0, 
    initial_condition=ic_q, 
    end_time=1.0, 
    output_path=os.path.join(output_dir, 'test_DG0'), 
    space_plot_vel=space_Vel, 
    expr_vel=expr_vel
    )
q_DG1 = solve_time_loop(
    name="advection DG(1)",
    weak_form_function=weak_form_advection, 
    functionspace=space_DG1, 
    initial_condition=ic_q, 
    end_time=1.0, 
    output_path=os.path.join(output_dir, 'test_DG1'), 
    space_plot_vel=space_Vel, 
    expr_vel=expr_vel
    )
Setup advection DG(0), solving PDE: 100%|██████████| 800/800 [00:03<00:00, 203.95it/s]
Setup advection DG(1), solving PDE: 100%|██████████| 2400/2400 [00:18<00:00, 127.87it/s]

We then generate plots to qualitatively check our solutions

q_0 = fem.Function(space_DG0, name=r'$q^n$')
q_0.interpolate(ic_q)
library.plot.scalar_fields(
    functions=[q_0, q_DG0],
    titles=["t=0", "t=1"],
    figurepath=output_dir,
    figurename='test_DG0',
    show_edges=False, 
    clim=[0.9, 2.1]
)

q_0 = fem.Function(space_DG1, name=r'$q^n$')
q_0.interpolate(ic_q)
library.plot.scalar_fields(
    functions=[q_0, q_DG1],
    titles=["t=0", "t=1"],
    figurepath=output_dir,
    figurename='test_DG1',
    show_edges=False, 
    clim=[0.9, 2.1]
)
image saved in /workspaces/cmm/content/exercises/notebooks/ex01/test_DG0.png
image saved in /workspaces/cmm/content/exercises/notebooks/ex01/test_DG1.png

Concentration of the Passive Tracer

\(DG(0)\)

library.plot.display_image(
    image_path=os.path.join(output_dir, 'test_DG0.png'))

\(DG(1)\)

library.plot.display_image(
    image_path=os.path.join(output_dir, 'test_DG1.png'))

Looking at the plots, we can draw two important conclusions:

  1. The \(DG(0)\) implementation is highly diffusive. This is due to the stabilizatoin in the local Lax-Friedrich/Rusanov numerical flux implementation. Using an Upwind flux instead would yield superior results.
  2. The \(DG(1)\) implementation violates the bounds of our initial condition, \(q \in [1, 2]\). As we have a pure advection equation without source (production) term, this behavior is unphysical! Usually, one would now implement so called limiters to control this problem. However, this is content of other courses focusing on the numerical details of such numerical methods.

A Passive Tracer in a Transient Velocity Field

Let us now try to simulate a slightly more complex case by replacing the static velocity field \(v(t,x) = (2,1)^T\) in our previous case with a transient and space dependent velocity field

\[ \mathbf{v} = \begin{cases} +\begin{pmatrix} -2(y-1.5) \\ 2(x-1.5) \end{pmatrix} & t \leq 0.5 \\ -\begin{pmatrix} -2(y-1.5) \\ 2(x-1.5) \end{pmatrix} & t > 0.5 \\ \end{cases} \]

In order to solve this case, we only need to define a new function for the weak form and can reuse all the other previously defined functions.

3. The weak form and UFL: From Math to Code

In the weak form function for transient advection, we update particularly

  • the advection velocity
  • the computation of \(|\lambda|_{\mathrm{max}}\)
def weak_form_advection_transient(functionspace, q_n, q_np1, t, x):

    # advection velocity
    sign = -(t-0.5)/abs(t-0.5)
    a = ufl.as_vector((-sign*2*(x[1]-1.5), sign*2*(x[0]-1.5)))

    # facet normals
    n = ufl.FacetNormal(domain)
    
    # integration measures domain, internal and boundary facets
    dx = ufl.dx
    dS = ufl.Measure("dS", domain=domain)
    facet_tags = library.helpers.generate_facets_tags(domain, P0, P1)
    ds = ufl.Measure("ds", domain=domain, subdomain_data=facet_tags)

    # time step size estimation
    basis_function_degree = functionspace.ufl_element().degree
    N = number_elements_x * number_elements_y
    dim = 2
    CFL = 1/(2*basis_function_degree+1)/dim
    
    # computing the maximum eigen value of the jacobian of flux
    a_x = fem.Function(functionspace)
    a_x.interpolate(
        fem.Expression(a[0], functionspace.element.interpolation_points())
        )
    a_y = fem.Function(functionspace)
    a_y.interpolate(
        fem.Expression(a[1], functionspace.element.interpolation_points())
        )
    max_abs_a = max(abs(a_x.x.array).max(), abs(a_y.x.array).max())
    
    characteristic_length = 1/max(number_elements_x, number_elements_y)
    _dt = CFL *characteristic_length / max_abs_a / 2
    dt = dolfinx.fem.Constant(domain, dolfinx.default_scalar_type(_dt))

    q = q_n
    q_extrapolation = q_n

    test_q = ufl.TestFunction(functionspace)
    trial_q = ufl.TrialFunction(functionspace)

    # numerical Lax-Friedrichs flux
    propagation_speed = abs(ufl.dot(a, n("+")))
    propagation_speed_bnd = abs(ufl.dot(a, n))

    numerical_flux = lambda qp, qm, a, n , propagation_speed: (
        ufl.dot(0.5 * (a*qp + a*qm), n)
            - 0.5 * propagation_speed * (qm - qp)
        )

    # weak formulation
    weak_form =  test_q * (trial_q-q)/dt * dx
    weak_form += - ufl.dot(ufl.nabla_grad(test_q), (a * q)) * dx
    weak_form += ufl.dot(
        (test_q("+") - test_q("-")), 
        numerical_flux(q("+"), q("-"), a, n("+"), propagation_speed)
        ) * dS
    weak_form += ufl.dot(
        (test_q), numerical_flux(q, q_extrapolation, a, n, propagation_speed_bnd)
        ) * (ds(1) + ds(2) + ds(3) + ds(4))
    
    weak_form_lhs = fem.form(ufl.lhs(weak_form))
    weak_form_rhs = fem.form(ufl.rhs(weak_form))

    return weak_form_lhs, weak_form_rhs, dt

6. Visualization: Comparing DG(0) and DG(1)

We now proceed by generating our \(DG(0)\) and \(DG(1)\) function spaces and use them along with our functions for the weak form, and initial conditions to solve the scalar advection equation and compare the results for \(DG(0)\) and \(DG(1)\).

space_DG0, space_DG1, space_Vel = generate_functionspaces(domain)
expr_vel = lambda t: lambda x: np.stack(
    ((t-0.5)/abs(t-0.5)*2*(x[1]-1.5), -(t-0.5)/abs(t-0.5)*2*(x[0]-1.5))
    )
q_DG0 = solve_time_loop(
    name="advection DG(0)",
    weak_form_function=weak_form_advection_transient,
    functionspace=space_DG0,
    initial_condition=ic_q,
    end_time=1.0, 
    output_path=os.path.join(output_dir, 'passivetracer_DG0'),
    space_plot_vel=space_Vel,
    expr_vel = expr_vel
    )
q_DG1 = solve_time_loop(
    name="advection DG(1)",
    weak_form_function=weak_form_advection_transient,
    functionspace=space_DG1,
    initial_condition=ic_q,
    end_time=1.0, 
    output_path=os.path.join(output_dir, 'passivetracer_DG1'),
    space_plot_vel=space_Vel,
    expr_vel = expr_vel
    )
Setup advection DG(0), solving PDE: 100%|██████████| 1188/1188 [00:04<00:00, 240.10it/s]
Setup advection DG(1), solving PDE: 100%|██████████| 3600/3600 [00:38<00:00, 93.87it/s] 

We then generate plots to qualitatively check our solutions

q_0 = fem.Function(space_DG0, name=r'$q^n$')
q_0.interpolate(ic_q)
library.plot.scalar_fields(
    functions=[q_0, q_DG0],
    titles=["t=0", "t=1"],
    figurepath=output_dir,
    figurename='passivetracer_DG0',
    show_edges=False, 
    clim=[0.9, 2.1]
)

q_0 = fem.Function(space_DG1, name=r'$q^n$')
q_0.interpolate(ic_q)
library.plot.scalar_fields(
    functions=[q_0, q_DG1],
    titles=["t=0", "t=1"],
    figurepath=output_dir,
    figurename='passivetracer_DG1',
    show_edges=False, 
    clim=[0.9, 2.1]
)
image saved in /workspaces/cmm/content/exercises/notebooks/ex01/passivetracer_DG0.png
image saved in /workspaces/cmm/content/exercises/notebooks/ex01/passivetracer_DG1.png

Concentration of the Passive Tracer

\(DG(0)\)

library.plot.display_image(
    image_path=os.path.join(output_dir, 'passivetracer_DG0.png'))

\(DG(1)\)

library.plot.display_image(
    image_path=os.path.join(output_dir, 'passivetracer_DG1.png'))

Verification

We now want to compute the L2-error of the \(DG(0)\) and \(DG(1)\) solutions by using the analytical solution.

For the given velocity field and the particular initial condition, the analytical solution is given by \(q^{\mathrm{analytical}}(t=1, x) = q(t=0, x)\).

Task 1

STUDENT TODO

Implement the verification by computing error_L2_DG0 and error_L2_DG1. Feel free to borrow as much code as possible from the ‘My first FEniCSx program’ notebook.

To test your implementation use the test_L2_error_implementation function below


error_L2_DG0 = 0.0 
error_L2_DG1 = 0.0
def test_L2_error_implementation(error_L2_DG0, error_L2_DG1):
    if abs(error_L2_DG0-0.21908372090991204) < 10**(-3):
        print("DG(0) L2 error test passed")
    else:
        print("DG(0) L2 error test failed")
        assert False
    if abs(error_L2_DG1-0.05223104872875855) < 10**(-3):
        print("DG(1) L2 error test passed")
    else:
        print("DG(1) L2 error test failed")
        assert False
test_L2_error_implementation(error_L2_DG0, error_L2_DG1)
DG(0) L2 error test failed
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[21], line 12
     10         print("DG(1) L2 error test failed")
     11         assert False
---> 12 test_L2_error_implementation(error_L2_DG0, error_L2_DG1)

Cell In[21], line 6, in test_L2_error_implementation(error_L2_DG0, error_L2_DG1)
      4 else:
      5     print("DG(0) L2 error test failed")
----> 6     assert False
      7 if abs(error_L2_DG1-0.05223104872875855) < 10**(-3):
      8     print("DG(1) L2 error test passed")

AssertionError: 

Streamlines and Pathlines

We would like to visualize the streamlines and pathlines of the velocity field to get a better understanding of the scalar advection problem.

Task 2

STUDENT TODO

Visualize the streamlines and pathlines in Paraview and insert an image for each into this notebook, using the cells below

#streamline plot
library.plot.display_image(image_path=None)
#pathline plot
library.plot.display_image(image_path=None)
Tip

To display a .png image, provide the path of the image to the image_path argument while calling the display_image functions

Prepare for your Presentation

During the presentation, be prepared to answer the following questions/tasks. We will ask 1-2 questions per person.

  1. What was this homework about?

  2. State the general transport equations and explain the role of each term

  3. Derive a particular part from the weak formulation of the unsteady advection equation for DG(1). E.g.

    1. Compute the weak form for a single element
    2. What is ambiguous at the facets and gives rise to the usage of a numerical flux function?
    3. What is the weak enforcement of boundary conditions? Where does this happen in the implementation of our weak form? Can we use it for Dirichlet and Neumann boundary conditions?
  4. Which terms of the weak formulation drops out if we restrict ourselves to DG(0) / CG(1)?

  5. How do you need to change the weak formulation if we want to introduce an inflow boundary condition with \(q|_{\partial\Omega^{\text{left}}}=q_{in} = 2\) on the left side of the domain.

  6. Create a streamline plot in paraview and explain what streamlines are

  7. Create a pathline plot in Paraview and explain what pathlines are