Timestepping

This example addresses and illustrates the following topics:

  • Definition of a simple parabolic equation
  • Dirichlet boundary condition
  • Definition of initial values
  • Two time stepping procedures, namely
    • Implicit Euler method
    • Limex method
  • Use of timing functions
  • Output of the result as .vtk and as time series

and can be found at tutorial/instationary_heattransfer in the Kaskade 7 repository. Execution of tutorials is described under Using the build environment in section Getting Started.

Introduction

This tutorial program solves a parabolic heat equation with Dirichlet boundary condition and an initial value condition by the use of two different time integration methods. It shows the definition of an initial value, the implementation of the time integration step, the use of timing methods to keep track on computation time and the output of time dependent results. In addition, we present some extension possibilities and show the results of this tutorial example.

Mathematical model

Motivation

This tutorial deals with a parabolic problem of the form \[ c \frac{\partial u}{\partial t} - \nabla \cdot (\kappa \nabla u) = f \quad x\text{ in } \Omega, 0 < t \leq T \] in the 2-dimensional region \( \Omega \) with Dirichlet boundary condition on the boundary \( \Gamma \) \[ u = u_b \quad \text{on } \Gamma = \partial \Omega \] and initial condition \[ u = u_0 \quad \text{on } \Omega \text{ for } t=0. \] After formulation as a variational problem and Galerkin discretization, the problem can be stated as a system of ODEs by \[ B\dot u = - Au + f \] with stiffness matrix \( A = \bigl( a(\varphi_i,\varphi_j)\bigr) _{i,j=1}^N \), \( a(\varphi_i,\varphi_j) = \int_\Omega \kappa \nabla \varphi_i \nabla \varphi_j dx \) and mass matrix \( B = \bigl((\varphi_i,\varphi_j)\bigr)_{i,j}^N \), \( (\varphi_i,\varphi_j) = \int_\Omega \varphi_i \varphi_j dx \).

The moving source example used for this tutorial shows a circulating moving source on a quadratic 2-dimensional unit grid. movingsource.gif

With \( \kappa=1 \) and \( c=1 \) and the use of \( p = x_1 - 0.25(2+\sin(\pi t)) \) and \( q = x_2 - 0.25(2+\cos(\pi t)) \) the PDE from above is implemented with the following parameters:

Initial condition \[ u_0 = 0.8\exp(-80((x_1-0.5)^2 + (x_2-0.75)^2)) \] Boundary condition \[ u_b = 0.8\exp(-80(p^2 + q^2)) \] Source term \[ f = u_b(-25600(p^2+q^2) + 320 + 40\pi (p \cos(\pi t) - q \sin(\pi t))) \]

Time discretization: Linearly implicit Euler

From the general formulation with constant matrix \( B \) in section linearly implicit Euler \[ (B-\tau L’(u_0))\delta u^k = \tau L(u^k) \] we can deduct the specific formulation for our tutorial example with the residual as functional \( L(u) := -Au+f \) \[ (B+\tau A)\delta u^k = -\tau (Au^k-f). \] with the displacement \( \delta u^k = u^{k+1}-u^k\). One solution step to solve this system of ODEs could then be performed by a direct inverse operation (as the simplest method among others) \[ \delta u^k = -(B+\tau A)^{-1}\tau (Au^k-f) \] resulting in the new iterate \( u^{k+1} = u^k + \delta u^k \).

LIMEX: Extrapolation method for linearly-implicit Euler

The Limex implementation in this tutorial example relies on the theory provided in section LIMEX. With basic stepsize \( H \) and definition of stepsizes \( \tau_j = \frac{H}{n_j} \) for the harmonic sequence \( n_j = 1,2,3, … \) we obtain different numerical solutions \( T_{j,1} \) at points \( (t_0 + H) \) by applying \( n_j \) steps of the linearly implicit Euler method \( \delta u^k = (B-\tau A)^{-1}\tau (Au^k-f) \).

In our tutorial example, we use extrapolation order 2. Hence, \( j_{max} = order+1 \), since in contrast to the pseudocode where \( j \) runs from 1 to \( j_{max} \), we loop over \( j \) from 0 to 2. To cancel out the higher order terms in the asymptotic expansion of the error of one basic approximation step, we set \( \gamma = 1 \). Then, the extrapolation formula of Aitken-Neville becomes \[ T_{j,k} = T_{j,k-1} + \frac{T_{j,k-1}-T_{j-1,k-1}}{\frac{n_j}{n_{j-k+1}}-1}, \qquad k=1,\ldots,j. \]

The extrapolation tableau with the linearly implicit Euler method as base method for LIMEX and extrapolation order 2 is given by \[ \begin{aligned} &T_{1,1} \\ &T_{2,1} && T_{2,2} \\ &T_{3,1} && T_{3,2} && T_{3,3} \end{aligned} \] where \( T_{1,1}, T_{2,1}, T_{3,1} \) correspond to order p from linearly implicit Euler. After a LIMEX step is performed, stepsize and order control is carried out by calculation of the temporal errors. Using the formula for setting a new basic stepsize provided in the theory section with \( p_j = j_{max}+1 = (\mathrm{order}+1) +1 = \mathrm{order}+2 \) and with \( \rho = 0.5 \): \[ H_{new} = \sqrt[\mathrm{order}+2]{0.5 \frac{\mathrm{eps}}{\epsilon}} H \] To prevent the stepsize factor from growing or shrinking too much, the factor \( \sqrt[\mathrm{order}+2]{0.5 \frac{\mathrm{eps}}{\epsilon}} \) gets bounded to 0.5 from below and 1.33 from above.

Deriving the domain and boundary caches

The domain cache with d1 and d2 defines the functions for assembly of mass and stiffness matrix and the right-hand side. Consider d0 as the domain part F of the variational functional of the elliptic equation (see section Variational functionals), derived by discretizing our parabolic equation: \[ \text{d0: } F(u) = -\frac{1}{2}\kappa \nabla u \cdot \nabla u + fu. \] Then, the caches d1 and d2 are calculated by the first and second Fréchet derivative in direction v and w of d0: \[ \begin{aligned} &\text{d1: } F’(u)[v] = -\kappa \nabla u \cdot \nabla v + fv \\ &\text{d2: } F’’(u)[v,w] = -\kappa \nabla v \cdot \nabla w \end{aligned} \] As it can be seen directly, the cache d2 resembles the stiffness matrix \( A \), while d1 is the right-hand side \( -Au+f \).

The boundary condition is implemented in the boundary cache by the Dirichlet penalty approach. Here, we define a penalty parameter \(\epsilon \rightarrow \infty\) and define the boundary integral as \( \int_\Gamma \frac{\epsilon}{2}(u-u_b)^2 dS \) in the variational functional. Consider d0 as the boundary part G of the variational functional: \[ \text{d0: } G(u) = \frac{\epsilon}{2} (u-u_b)^2. \] Then, the d1 and d2 caches are calculated again by the first and second Fréchet derivative in direction v and w of d0: \[ \begin{aligned} &\text{d1: } G’(u)[v] = \epsilon(u-u_b)v \\ &\text{d2: } G’’(u)[v,w] = \epsilon vw \end{aligned} \]

Treatment of mass matrix

The mass matrix is built separately in the cache b2. Starting from \( \frac{1}{2} c u^2 \) after discretization and formulation in the variational functional, the b2 domain cache is again the second Fréchet derivative and simply defined as \[ \text{b2: } B’’(u)[v,w] = cvw \] The b2 boundary cache is set to zero.

Source code documentation

Overall structure of the tutorial program code

The following list shows the header files used in this tutorial. Some of them are only needed for optional output or timing and can be omitted in a minimal program:

#include <iostream>
#include <bits/stdc++.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <boost/timer/timer.hpp>            // for use of cpu timer

#include "dune/grid/config.h"               // in dune libraries
#include "dune/grid/uggrid.hh"              // in dune libraries

#include "fem/gridmanager.hh"
#include "fem/lagrangespace.hh"

#include "io/vtk.hh"                        // input/output methods
#include "io/vtkreader.hh"

#include "timestepping/limexWithoutJens.hh" // limex with embedded error estimation
#include "utilities/gridGeneration.hh"      // create unit squares and cubes
#include "utilities/kaskopt.hh"             // for command line option parsing
#include "timestepping/semieuler.hh"        // define weak formulation for semi implicit euler

using namespace Kaskade;

#include "integrate.hh"
#include "movingsource.hh"

Create a Makefile in the same directory:

include /kaskade7/Makefile.Local
include $(KASKADE7)/Makefile.Rules

FLAGS += -g -Wall

ALLLIBS = $(KASKADELIB) $(DUNELIB) $(UGLIB) $(BOOSTLIB) $(DIRECTSOLVERLIB) $(BLASLIB) $(FTNLIB) $(NUMALIB)

movingsource: movingsource.o $(KASKADE7)/libs/libkaskade.a
	$(CXX) $(FLAGS) $< $(KASKADE7)/libs/*.o $(ALLLIBS) $(LINKFLAGS) -o $@

Build and run the two variants with

make movingsource.d
make movingsource
./movingsource --semiimplicit 1 --stepsize 0.05
./movingsource --semiimplicit 0 --stepsize 0.025

The dependency file must be generated first; see the Hello World section for the reason. The program creates the output directory graph itself.

The following steps define this tutorial program:

  • creation of initial values
  • setting up the spaces
  • creating the grid
  • defining the equation of our problem
  • creating the assembler
  • solving: time-stepping and assembly
  • solution output

Classes and functions in detail

Setting up the equation

To define our problem equation in Kaskade, we use the class MovingSourceEquation. Then, the equation is defined in the main function by

using Equation = MovingSourceEquation<double,VariableSet>;
Equation Eq(c,kappa); // e.g. c capacity, kappa conductivity

The domain and boundary caches (see section Deriving the domain and boundary caches) are implemented in this class in the header file movingsource.hh, as well as evaluation methods, the source term and functionalities to get and set the parameters for heat conduction, heat capacity and so on. The caches are used by the assembler via the class SemiImplicitEulerStep to build the left-hand side of our problem (i.e. stiffness and mass matrix) and the right-hand side. To sum up, in the header file we implement

  • our problem equation in class MovingSourceEquation
  • the class DomainCache for domain caches d1, d2 and b2
  • the class BoundaryCache for boundary caches d1, d2 and b2 and the penalty parameter
  • evaluation methods in evaluateAt for e.g. the source term, the variables and their derivatives, etc.
  • get and set parameters of the equation
  • helper methods and structures for assembly, time integration and initial values

evaluateAt evaluation method:

    template <class Position, class Evaluators>
    void evaluateAt(Position const& x, Evaluators const& evaluators)
    {
      using namespace boost::fusion;
      auto xglob = e->geometry().global(x);

      u = vars.template value<0>(evaluators);
      du = vars.template derivative<0>(evaluators)[0];
      t = F.time();

      double vx = xglob[0]-0.25*(2.0 + sin(3.14159265358979323846*t));
      double vy = xglob[1]-0.25*(2.0 + cos(3.14159265358979323846*t));
      double h = 0.8*exp(-80.0*(vx*vx + vy*vy));
      double vt = vx * cos(3.14159265358979323846*t) - vy * sin(3.14159265358979323846*t);
      double g  = -25600.0 * ( vx*vx + vy*vy) + 320.0 + 3.14159265358979323846*40.0*vt;
      f = h*g; // create source term f
    }

Domain cache: The right-hand side is built in d1, the stiffness matrix is built in d2:

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
      return -F.kappa*du*arg.derivative[0] + f*arg.value;
    }

    template<int row, int col, int dim>
    Dune::FieldMatrix<Scalar, TestVars::template Components<row>::m, AnsatzVars::template Components<col>::m>
    d2 (VariationalArg<Scalar,dim> const &arg1, VariationalArg<Scalar,dim> const &arg2) const
    {
      return -F.kappa*arg1.derivative[0]*arg2.derivative[0];
    }

The mass matrix is built in b2. Note: This cache is not directly evaluated by the assembler and requires the construction of a ParabolicEquation in the class SemiImplicitEulerStep. The b2 cache then gets evaluated by this proxy class and handed over to the assembler as d2.

    template<int row, int col, int dim>
    Dune::FieldMatrix<Scalar, TestVars::template Components<row>::m, AnsatzVars::template Components<col>::m>
    b2 (VariationalArg<Scalar,dim> const &arg1, VariationalArg<Scalar,dim> const &arg2) const
    {
      return F.c*arg1.value[0]*arg2.value[0];
    }

Boundary cache: The boundary conditions are implemented in the same way as the domain:

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
      return penalty*(u-ub)*arg.value[0];
    }
    template<int row, int col, int dim>
    Dune::FieldMatrix<Scalar, TestVars::template Components<row>::m, AnsatzVars::template Components<col>::m>
    d2 (VariationalArg<Scalar,dim> const &arg1, VariationalArg<Scalar,dim> const &arg2) const
    {
      return penalty*arg1.value*arg2.value;
    }
    template<int row, int col, int dim>
    Dune::FieldMatrix<Scalar, TestVars::template Components<row>::m, AnsatzVars::template Components<col>::m>
    b2 (VariationalArg<Scalar,dim> const &arg1, VariationalArg<Scalar,dim> const &arg2) const
    {
      return 0;
    }

The penalty parameter has to be defined as well. It is set to a very large number, here 109:

    void moveTo(FaceIterator const& entity)
    {
      e = &entity;
      penalty = 1.0e9; // for Dirichlet boundary condition
    }

We can provide additional information about our problem by defining structures struct for the assembly. In this example our mass matrix \( B \) does not depend on \( u \). Therefore, we set the parameter constant = true in B2. Further, our stiffness matrix is symmetric, same holds for the mass matrix, and we set the parameter symmetric = true in D2 and B2. Other parameters depending on the problem definition can be added to B2 such as mass lumping via lumping = true, if required and applicable:

template <int row>
  struct D1: public FunctionalBase<WeakFormulation>::D1<row>
  {
    static bool const present   = true;
    static bool const constant  = false;
  };

  template <int row, int col>
  struct D2: public FunctionalBase<WeakFormulation>::D2<row,col>
  {
    static bool const present = true;
    static bool const symmetric = true;
    static bool const lumped = false;
  };

  template <int row, int col>
  struct B2
  {
    static bool const present   = true;
    static bool const symmetric = true;
    static bool const constant  = true;
    static bool const lumped = false;
  };

Hint: It is possible as well to define a cache d0 for domain and boundary in the header file (not implemented in the tutorial) for a problem based on a variational functional. This d0 cache can be accessed via the assembler. Then, one could use this

Scalar
  d0() const
  {
    return -(F.kappa*du*du)/2 + f*u;
  }

and the corresponding formulation for the boundary condition in the boudary cache to evaluate the functional in our main program by calling

  double val = assembler.functional();

How would you implement different Dirichlet boundary conditions on each side of the square? Hint: Use xglob from the evaluateAt function.

Time The variable \( t\) is acessible by the methods:

  Scalar time() const { return t; }
  Self& setTime(Scalar tnew)  { t = tnew; return *this; }

Setting \( t\) with the latter is necessary in timestepping, if the equation depends explicitly on time.

Initial value definition

In the Galerkin method, our initial condition \(u(0,x)=u_0(x) \) is expressed as \( u_0(x) = \sum_{j=1}^N u_{0,j} \varphi_j \). Hence, we have to set the initial condition properly by defining the values \( u_{0,j} \) in the finite element mesh as so-called “function space elements”. Since we cannot do this manually for all nodes, the initial values are interpolated and assigned with help of functions in Kaskade 7 that implement the basic concepts:

  • the new user-defined data type InitialValue
  • the user-defined method scaleInitialValue in the header file
  • the basic Kaskade 7 interpolation method interpolateGloballyWeak
  • the Kaskade 7 concepts of WeakFunctionView and FunctionSpaceElement

In the main file, the initial value \( u_0(x) \) is set by the use of the user-defined data type InitialValue. Here, in a two-dimensional setting, the initial value is the Gaussian peak used by the moving-source example:

struct InitialValue
{
  using Scalar = double;
  static int const components = 1;
  using ValueType = Dune::FieldVector<Scalar,components>;

  InitialValue(int c): component(c) {} // constructor

  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }
  template <class Cell>
  ValueType value(Cell const& cell,
                  Dune::FieldVector<typename Cell::Geometry::ctype,Cell::dimension> const& localCoordinate) const
  {
    Dune::FieldVector<typename Cell::Geometry::ctype,Cell::Geometry::coorddimension> x = cell.geometry().global(localCoordinate);

    double vx = x[0]-0.5;
    double vy = x[1]-0.75;

    return 0.8*exp(-80.0*(vx*vx + vy*vy)); // the initial value
  }

private:
  int component;
};

Then, the initial value of the equation is assigned by method scaleInitialValue, defined in the header file, which transforms the values into proper finite element iterates:

  using Equation = MovingSourceEquation<double,VariableSet>;

  Equation Eq(c,kappa); // e.g. c capacity, kappa conductivity

  Eq.scaleInitialValue<0>(InitialValue(0),x); // VariableSet x, Gaussian initial value

The definition in the header by using the lambda function makeWeakFunctionView file looks as follows:

template <int row, class WeakFunctionView>
  void scaleInitialValue(WeakFunctionView const& u0, typename AnsatzVars::VariableSet& u) const
  {
    interpolateGloballyWeak(boost::fusion::at_c<row>(u.data),
                            makeWeakFunctionView([u0](auto const& cell, auto const& xi)
                            {
                              return u0.value(cell,xi);
                            }));
  }

Here, the interpolateGloballyWeak method makes it possible to transform a WeakFunctionView to a FunctionSpaceElement by interpolation. A WeakFunctionView is basically a class that supports efficient evaluation by cell and local coordinate (at the evaluation point in the cell), whileas a FunctionView is a function that supports evaluation by an evaluator.

An alternative is to use the helper data type ScaledFunction for creating interpolates by interpolateGloballyWeak. It wraps a WeakFunctionView together with the equation and can apply an equation-specific scaling during interpolation:

  interpolateGloballyWeak<Volume>(boost::fusion::at_c<row>(u.data),ScaledFunction<WeakFunctionView>(true,u0,*this));

Now, we have successfully transformed our initial value to a FunctionSpaceElement for calculation, which is simply the representation of a component of the underlying finite element function space.

Try setting an initial value on your own and observe what changes.

Implementing the Euler steps

The class SemiImplicitEulerStep defines the weak formulation of this stationary elliptic problem, resulting from time discretization of a parabolic PDE, and provides the implementation of \( B-\tau A \) and right hand side \( \tau (Au^k-f) \) for assembly. The matrices \( A \), \( B \) and the vector \( (Au^k-f) \) are assembled based on the d1, d2 and b2 caches in the corresponding header file movingsource.hh of the parabolic equation, see section Setting up the equation.

The class SemiLinearizationAt is a proxy class for the linearization of semi-linear time stepping schemes. In addition to the current state, it uses a linearization point \( u_0 \) for the Jacobian \( L’(u_0) \). The linearly implicit Euler step is obtained from \( B\dot u = L(u) \) by replacing \( L(u^{k+1}) \) with its first-order Taylor expansion around \( u_0 \), which yields \[ (B-\tau L’(u_0)),\delta u^k = \tau L(u^k). \]

for (int i=0; i<MaxIter; ++i)
    {
      SemiImplicitEulerStep<Equation> eq(&Eq,dt);
      double const tau = dt;
      eq.setTau(tau);

      assembler.assemble(Linearization(eq,x,x,dx));
      AssembledGalerkinOperator<Assembler> A(assembler);

      auto step = variableSet.zeroCoefficientVector();
      auto rhs = assembler.rhs();

      directInverseOperator(A,DirectType::UMFPACK,MatrixProperties::GENERAL).applyscaleadd(1,rhs,step);
      component<0>(x) += component<0>(step);
      Eq.setTime(Eq.time()+dt);
    }

where

  using Linearization = SemiLinearizationAt<SemiImplicitEulerStep<Equation>>;
  using Assembler = VariationalFunctionalAssembler<Linearization>;

In each step, the system is solved by a simple direct inverse operation and the new iterate \( u^{k+1} = u^k +\delta u^k \) is calculated, until the maximum number MaxIter of desired iterations is reached.

Perform time integration with LIMEX

Time-integration according to the Limex theory section and Limex tutorial section is performed within the header file integrate.hh which calls the Limex from timestepping/limexWithoutJens.hh. The basic stepsize for the current iteration is set and followed by one step of Limex. Afterwards, the temporal error is estimated for this step and used to calculate the next basic stepsize. Hence, this is an adaptive method for calculating good basic stepsizes.

The procedure is as follows:

  • construct LIMEX integrator for time integration,
  • loop over number of desired steps to perform time stepping with LIMEX and
  • adapt basic stepsize by estimated errors after each step.

First, the LIMEX integrator has to be constructed, templated by our PDE equation and based on the grid, the specific equation, the variables and the choice of a direct or iterative solver and a preconditioner:

Limex<Equation> limex(gridManager,eq,variableSet,directType,PrecondType::ILUK,verbosity);

The steps of the time integration then are performed as follows:

for (steps=0; !done && steps<maxSteps; ++steps)
{
  [...]

  dt *= factor; // set new basic stepsize
  dx = limex.step(x,dt,extrapolOrder,tolX); // perform one step of LIMEX
  std::vector<std::pair<double,double> > errors = limex.estimateError(x,extrapolOrder,extrapolOrder-1); // errors in time

  [adapt stepsize]
}

Calculation of the factor for the next basic stepsize relies on the subdiagonal error, the desired accuracy, a safety factor and the extrapolation order:

dt *= factor;

[limex step with new dt]

std::vector<std::pair<double,double> > errors = limex.estimateError(x,extrapolOrder,extrapolOrder-1); // subdiagonal errors
err = 0;
for (int i=0; i<errors.size(); ++i)
  err = std::max(err, errors[i].first/(tolT[i].first+tolT[i].second*errors[i].second)); // subdiagonal errors and accuracy

factor = std::pow(0.5/err,1./(extrapolOrder+2)); // safety factor = 0.5
factor = std::max(0.5,std::min(factor,1.33)); // bound factor from above and below

Here, errors = limex.estimateError(x,p,p-1) provides the subdiagonal errors and the current state such that for each i, errors[i].first gives the subdiagonal error \( |T_{p,p}-T_{p,p-1}| \) with \( p \) as the extrapolation order and errors[i].second gives the current state \( u \). If our problem is defined in more than on variable or solution component \( u \), the i iterates over the number of variables/solution components to find the largest overall error. Then, the quotient \( \mathrm{err} = \frac{\epsilon}{\mathrm{eps}} \) is calculated. The update factor for the new basic stepsize \( H_{new} \) is calculated with safety factor \( 0.5 \), yielding \( \frac{0.5}{\mathrm{err}} = 0.5\frac{\mathrm{eps}}{\epsilon} \) to the power of \( \frac{1}{\mathrm{order}+2 } \). To prevent the stepsize factor from growing or shrinking too much, the factor gets bounded to \( 0.5 \) from below and \( 1.33 \) from above.

One step of Limex computes a state increment dx that advances the given current state x in time. Setting an extrapolation order of zero simply corresponds to the linearly implicit Euler without calculation of higher order approximations. The for-loop in i calculates the \( T_{j,1} \), while the propagation loop over j calculates the higher-order approximations and the \( T_{j,j} \) during the push_back into the extrapolation tableau. This happens in timestepping/limexWithoutJens.hh, where the LIMEX algorithm is implemented as follows:

State const& step(State const& x, double dt, int order, std::vector<std::pair<double,double>> const& tolX)
{
  for (int i=0; i<=extrapolationorder; ++i)
  {
    [calculate step fractions tau]
    // mesh adaption loop if spatial error too large, expressed by variable "accurate"
    do {
      [assemble current system]
      [solve system yielding increment dx]
      [perform mesh adaption] // only if in first stage of Euler step i=0
    } while (!accurate);
    [set new state increment, dxsum = dx]

    // propagation for tableau
    if (extrapolationorder==0)
    {
      [insert dxsum into extrapolation tableau] // theory: T_1,1
      [return last state increment]
    }
    else
    {
      for (int j=1; j<=i; ++j)
      {
        [assemble system with new rhs x+dx]
        [solve system]
        [add new state increment dx to previous one, dxsum += dx]
      }
    }
    [insert dxsum into extrapolation tableau] // theory: T_j,1
  }
  [return last state increment] // theory: T_j,j
}

The class ExtrapolationTableau handles the calculation of the higher-order approximations \( T_{j,k} \) and \( T_{j,j} \) by the Aitken-Neville formula during insertion into the tableau by extrap.push_back(dxsum,stepFractions[i]).

Estimation of errors

After a LIMEX step, limex.estimateError(x,extrapolOrder,extrapolOrder-1) returns the subdiagonal error estimates together with the corresponding state values. For each solution component \(i\), the error is normalized by the absolute and relative tolerances, \[ \mathrm{err}_i = \frac{\epsilon_i}{\mathrm{aTolT}_i + \mathrm{rTolT}i |u_i|}, \] and the maximum over all components is used as the error measure err. The next basic stepsize is then chosen as \[ H{\text{new}} = H \left(\frac{\rho}{\mathrm{err}}\right)^{1/(\mathrm{order}+2)} \] with safety factor \(\rho=0.5\), and the factor is clipped to the interval \([0.5,1.33]\) to avoid excessively large or small steps. If err > 1, the step is rejected and repeated with a smaller stepsize. This is the subdiagonal error criterion described in the LIMEX section.

Measure program execution times: Timings vs. Boost Timer

Sometimes it is useful to know how long a program takes for execution. Such timing information may be divided into wall time, user CPU time and system CPU time. Wall time is the time that a clock on the wall would measure between start of the process and now. The amount of time spent in user code (your program code and code from third-party libraries) is the user CPU time, while the amount of time spent in kernel code (code that is part of the operating system) is the system CPU time. Units are in seconds. On a single core machine, wall time will be always greater than CPU time. Using multi-core machines and multi-threaded programs, this can cause multiple CPU seconds of effort per second of elapsed wall time. The two methods presented here base on the implementation of

  • boost::timer::cpu_timer from boost libraries and
  • the Timings class, implemented in Kaskade 7.

A handy tool is the boost::timer::cpu_timer from boost libraries. A detailed explanation can be found here: Boost Timer. In this tutorial example, a timer for the execution of the whole program is set and accompanied by timers for assembly and solution within the semi-implicit Euler method. When the timer object is created, it starts the time measurement.

boost::timer::cpu_timer totalTimer;
std::cout << "Start moving source tutorial program" << std::endl;

[program code]

std::cout << "Total cpu time: " << totalTimer.format() << "\n";
std::cout << "End moving source tutorial program" << std::endl;

Calling format() at any point to get elapsed time as wall, user and system time. Using the member function elapsed() instead lets you chose between output of only wall, user or system time. Timers can be started, stopped and resumed. Calling start() restarts the timer from zero. To measure e.g. the time used for assembly over the whole loop, create a variable assemblyTime and sum up the elapsed time:

double assemblyTime = 0; // initialize before accumulating
for (int i=0; i<MaxIter; ++i) // time integration loop
{
  [...]
  timer.start();
  assembler.assemble(Linearization(eq,x,x,dx));
  assemblyTime += (double)(timer.elapsed().user)/1e9; // measured in user time
  [...]
}
std::cerr << "Euler: " << assemblyTime << "s assembly\n" << std::flush;

The elapsed time is here measured in user time, but could as well be measured in wall time timer.elapsed().wall, system time timer.elapsed().system or all three together.

Accumulators such as assemblyTime and solutionTime must be initialized to zero before the first +=. The current repository version of movingsource.cpp declares them without an initializer, which yields undefined values in the timing report. Initialize them as shown above.

This can be done for other parts of the program in the same manner, as shown for the solutionTime in the Euler section, i.e. the time the direct inverse operator takes to solve the system.

Another option is the use of the Timings class, implemented in Kaskade 7. It is used to gather and report execution times information for nested program parts. As well, for timing investigation in multithreaded computations, the class TaskTiming can be used, yielding a gnuplot file to visualize task durations. After creating of an instance of Timings, the part of interest has to be wrapped in start() and stop() and labeled by a certain name. To set the timer back to zero, call clear(). This could look as follows:

Timings& timings = Timings::instance();

for (int i=0; i<MaxIter; ++i) // time integration loop
{
  [...]
  timings.start("matrix assembly");
  assembler.assemble(Linearization(eq,x,x,dx));
  timings.stop("matrix assembly");
  [...]
  std::cout << "Setup:" << timings;
  timings.clear();
}

This procedure gives you a detailed overview of the execution times of the processes, assigned to their given names and arranged in the order of their creation.

Try using the Kaskade Timings class by yourself and exchange the boost::timer parts in the tutorial example. Is the Timer output more suitable for you than the boost::timer?

Writing sampled data

For comparing simulation results with measurements, it is often useful to record the solution at a fixed sample position over time. This is demonstrated in the semi-implicit Euler loop and in the LIMEX integration method by the use of a static std::ofstream. Data at the specified sample position is written into a plain text file together with its time stamp, and can afterwards be plotted with gnuplot, Python/matplotlib, or Matlab:

Dune::FieldVector<double,2> samplePos(0);
samplePos[0] = 0.5;
samplePos[1] = 0.2;
[...]
static std::ofstream sampleOut("samplepositionEuler.dat"); // data file: output of result at sample position
sampleOut << std::to_string(Eq.time()) << ' ' << component<0>(x).value(samplePos)[0] << std::endl;

This is especially useful for comparing measurement data taken at a certain sample position with simulated data and generating measurement curves.

Writing time series in .vtk format

The semi-implicit Euler loop writes one VTK file per time step, graph/SemiImplicit000.vtu, graph/SemiImplicit001.vtu, and so on. The zero-padded number is created with paddedString:

writeVTK(x,"graph/SemiImplicit"+paddedString(i,3),
         IoOptions().setOrder(order).setPrecision(7).setDataMode(IoOptions::nonconforming));

ParaView can load such a numbered sequence as a time series. Alternatively, use the class TimeSeriesVTKWriter, which writes the individual .vtu files and a .pvd collection file that ParaView reads directly:

TimeSeriesVTKWriter writer("graph/movingSource",IoOptions().setOrder(order).setPrecision(7));
for (int step=0; step<numSteps; ++step)
  writer.add(time[step],solution[step]);

See Output for details on VTK output and IoOptions.

Complete header files

The following two headers contain the equation, the initial-value helper and the LIMEX time-integration loop. They are reproduced here so that the example is self-contained; the same files are available in tutorial/instationary_heattransfer in the Kaskade 7 repository.

movingsource.hh

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*  This file is part of the library KASKADE 7                               */
/*  https://www.zib.de/research/projects/kaskade7-finite-element-toolbox     */
/*                                                                           */
/*  Copyright (C) 2002-2023 Zuse Institute Berlin                            */
/*                                                                           */
/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */
/*    see $KASKADE/academic.txt                                              */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#ifndef MOVINGSOURCE_HH
#define MOVINGSOURCE_HH

#include <cmath>

#include "fem/fixdune.hh"
#include "fem/variables.hh"


int printCount = 10;

/**
 * \brief An instationary heat equation.
 *
 * The right hand side (source term) and Dirichlet boundary conditions are defined by
 * the method of manufactured solutions such that the exact solution is a Gauss peak
 * rotating in the unit square.
 */
template <class RType, class VarSet>
class MovingSourceEquation: public FunctionalBase<WeakFormulation>
{
  using Self = MovingSourceEquation<RType,VarSet>;
public:
  using Scalar = RType;
  using AnsatzVars = VarSet;
  using TestVars = VarSet;
  using OriginVars = VarSet;

  using GridView = typename OriginVars::GridView;


  using Cell = Kaskade::Cell<GridView>;
  using Position = LocalPosition<GridView>;

  static constexpr int dim = GridView::dimension;

  class DomainCache
  {
  public:
    DomainCache(Self const& F_,
                typename AnsatzVars::VariableSet const& vars_,int flags=7):
      F(F_), vars(vars_)
    {}

    void moveTo(Cell const &entity) { e = &entity; }

    template <class Position, class Evaluators>
    void evaluateAt(Position const& x, Evaluators const& evaluators)
    {
      using namespace boost::fusion;
      auto xglob = e->geometry().global(x);

      u = vars.template value<0>(evaluators);
      du = vars.template derivative<0>(evaluators)[0];
      t = F.time();

      double vx = xglob[0]-0.25*(2.0 + sin(3.14159265358979323846*t));
      double vy = xglob[1]-0.25*(2.0 + cos(3.14159265358979323846*t));
      double h = 0.8*exp(-80.0*(vx*vx + vy*vy));
      double vt = vx * cos(3.14159265358979323846*t) - vy * sin(3.14159265358979323846*t);
      double g  = -25600.0 * ( vx*vx + vy*vy) + 320.0 + 3.14159265358979323846*40.0*vt;
      f = h*g; // create source term f
    }

    template<int row>
    D1Result<TestVars,row>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
      return -F.kappa*du*arg.derivative[0] + f*arg.value;
    }

    template<int row, int col>
    D2Result<TestVars,row,AnsatzVars,col>
    d2 (VariationalArg<Scalar,dim> const& argT, VariationalArg<Scalar,dim> const& argA) const
    {
      return -F.kappa*argT.derivative[0]*argA.derivative[0];
    }

    template<int row, int col>
    D2Result<TestVars,row,AnsatzVars,col>
    b2 (VariationalArg<Scalar,dim> const& argT, VariationalArg<Scalar,dim> const& argA) const
    {
      return F.c*argT.value[0]*argA.value[0];
    }

  private:
    Self const& F;
    typename AnsatzVars::VariableSet const& vars;

    Cell const* e;

    Scalar u, t, f;
    Dune::FieldVector<Scalar,AnsatzVars::Grid::dimension> du;
  };

/// \class BoundaryCache
///
  class BoundaryCache
  {
  public:
    using FaceIterator = typename AnsatzVars::Grid::LeafIntersectionIterator;

    BoundaryCache(Self const& F_,
                  typename AnsatzVars::VariableSet const& vars_,int flags=7):
      F(F_), vars(vars_), e(0)
    {}

    void moveTo(FaceIterator const& entity)
    {
      e = &entity;
      penalty = 1.0e9; // for Dirichlet boundary condition
    }

    template <class Evaluators>
    void evaluateAt(Dune::FieldVector<typename AnsatzVars::Grid::ctype,AnsatzVars::Grid::dimension-1> const& x,
                    Evaluators const& evaluators)
    {
      using namespace boost::fusion;

      int const TIdx = result_of::value_at_c<typename AnsatzVars::Variables,0>::type::spaceIndex;
      Dune::FieldVector<typename AnsatzVars::Grid::ctype,AnsatzVars::Grid::dimension> xglob = (*e)->geometry().global(x);
      u = at_c<0>(vars.data).value(at_c<TIdx>(evaluators));
      t = F.time();

      double vx = xglob[0]-0.25*(2.0 + sin(3.14159265358979323846*t));
      double vy = xglob[1]-0.25*(2.0 + cos(3.14159265358979323846*t));

      ub = 0.8*exp(-80.0*(vx*vx + vy*vy)); // create boundary value
    }

    template<int row>
    D1Result<TestVars,row>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
      return penalty*(u-ub)*arg.value[0];
    }

    template<int row, int col>
    D2Result<TestVars,row,AnsatzVars,col>
    d2 (VariationalArg<Scalar,dim> const &arg1, VariationalArg<Scalar,dim> const &arg2) const
    {
      return penalty*arg1.value*arg2.value;
    }

    template<int row, int col>
    D2Result<TestVars,row,AnsatzVars,col>
    b2 (VariationalArg<Scalar,dim> const &arg1, VariationalArg<Scalar,dim> const &arg2) const
    {
      return 0;
    }

  private:
    Self const& F;
    typename AnsatzVars::VariableSet const& vars;
    FaceIterator const* e;
    Scalar penalty, u, ub, t;
  };

  class Scaling
  {
  public:
    Scaling(Self const& self_): self(&self_) {}

    template <class Vals>
    void scale(Cell const&, Position const&, Vals& vals) const
    {
    }
    template <class Vals>

    void operator()(Cell const& cell, Position const& xi, Vals& vals) const
    {
      scale(cell,xi,vals);
    }

  private:
    Self const* self;
  };

/// \struct D2
///

public:

  Scalar time() const { return t; }

  Self& setTime(Scalar tnew)  { t = tnew; return *this; }

  Scaling scaling() const { return Scaling(*this); }
  void temporalEvaluationRange(double t0, double t1) { tau = t1-t0; }

  template <int row>
  struct D1: public FunctionalBase<WeakFormulation>::D1<row>
  {
    static bool const present   = true;
    static bool const constant  = false;
  };

  template <int row, int col>
  struct D2: public FunctionalBase<WeakFormulation>::D2<row,col>
  {
    static bool const present = true;
    static bool const symmetric = true;
    static bool const lumped = false;
  };

  template <int row, int col>
  struct B2
  {
    static bool const present   = true;
    static bool const symmetric = true;
    static bool const constant  = true;
    static bool const lumped = false;
  };

  MovingSourceEquation(double c_, double kappa_)
  : c(c_), kappa(kappa_)
  {}
  /**
   * Given an initial value, this is transfered to a properly scaled
   * finite element iterate.
   */
  template <int row, class WeakFunctionView>
  void scaleInitialValue(WeakFunctionView const& u0, typename AnsatzVars::VariableSet& u) const
  {
    interpolateGloballyWeak(boost::fusion::at_c<row>(u.data),
                            makeWeakFunctionView([u0](auto const& cell, auto const& xi)
                            {
                              return u0.value(cell,xi);
                            }));
  }

/// \fn integrationOrder
///

  template <class Cell>
  int integrationOrder(Cell const& /* cell */, int shapeFunctionOrder, bool boundary) const
  {
    if (boundary)
      return 2*shapeFunctionOrder;
    else
      return 2*shapeFunctionOrder+1;
  }

private:
  Scalar t = 0.0, tau;
  Scalar c, kappa;
  template <class WeakFunctionView>
  struct ScaledFunction
  {
    using Scalar = typename WeakFunctionView::Scalar;
    static int const components = WeakFunctionView::components;
    using ValueType = Dune::FieldVector<Scalar,components>;

    ScaledFunction(bool doScaling_,
                   WeakFunctionView const& u0_,
                   MovingSourceEquation<RType,AnsatzVars> const& f_): doScaling(doScaling_), u0(u0_), f(f_) {}

    template <class Cell>
    int order(Cell const&) const { return std::numeric_limits<int>::max(); }

    template <class Cell>
    ValueType value(Cell const& cell,
                    Dune::FieldVector<typename Cell::Geometry::ctype,Cell::dimension> const& localCoordinate) const
    {
      ValueType u = u0.value(cell,localCoordinate);
      return u;
    }

  private:
    bool doScaling;
    WeakFunctionView const& u0;
    MovingSourceEquation<RType,AnsatzVars> const& f;
  };

};
/// \example movingsource.cpp
/// show the usage of MovingSourceEquation describing an instationary heat transfer problem,
/// time discretization is done by semi-implicit Euler or LIMEX, spatial discretization by FEM using an embedded
/// error estimation.
///
#endif

integrate.hh

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*  This file is part of the library KASKADE 7                               */
/*  https://www.zib.de/research/projects/kaskade7-finite-element-toolbox     */
/*                                                                           */
/*  Copyright (C) 2002-2023 Zuse Institute Berlin                            */
/*                                                                           */
/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */
/*    see $KASKADE/academic.txt                                              */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#ifndef INTEGRATE_HH
#define INTEGRATE_HH

#include "fem/coarsening.hh"
#include "utilities/enums.hh"

template <class Grid, class Equation, class VariableSet, class Spaces, class OutIter>
typename VariableSet::VariableSet  integrate(GridManager<Grid>& gridManager,
                                             Equation& eq, VariableSet const& variableSet, Spaces const& spaces,
                                             double dt, double dtMax,
                                             double T, int maxSteps, double rTolT, double aTolT,
                                             double rTolX, double aTolX, int extrapolOrder,
                                             OutIter out, double outInterval,
                                             typename VariableSet::VariableSet x,
                                             Dune::FieldVector<double,2> samplePos,
                                             DirectType directType,
                                             int verbosity = 0)
{
  // absolute and relative spatial error tolerances
  std::vector<std::pair<double,double> > tolX(variableSet.noOfVariables);
  for (int i=0; i<tolX.size(); ++i)
    tolX[i] = std::make_pair(aTolX,rTolX);

  // absolute and relative temporal error tolerances
  std::vector<std::pair<double,double> > tolT(variableSet.noOfVariables);
  for (int i=0; i<tolT.size(); ++i)
    tolT[i] = std::make_pair(aTolT,rTolT);

  // create an instance of LIMEX
  Limex<Equation> limex(gridManager,eq,variableSet,directType,PrecondType::ILUK,verbosity);

  static std::ofstream sampleOut("samplepositionLimex.dat"); // data file: output of result at sample position

  int steps;
  bool done = false;
  for (steps=0; !done && steps<maxSteps; ++steps)
  {
    if (eq.time()>T-1.1*dt)
    {
      dt = T-eq.time();
      done = true;
    }

    typename VariableSet::VariableSet dx(x);

    int redMax = 5;
    int red = 0;
    double factor = 1.0;
    double err;

    do {
      dt *= factor; // set new basic stepsize
      dx = limex.step(x,dt,extrapolOrder,tolX); // perform one step of LIMEX
      if (extrapolOrder > 0)
      {
        std::vector<std::pair<double,double> > errors = limex.estimateError(x,extrapolOrder,extrapolOrder-1); // errors in time
        err = 0;
        for (int i=0; i<errors.size(); ++i)
          err = std::max(err, errors[i].first/(tolT[i].first+tolT[i].second*errors[i].second));

        factor = std::pow(0.5/err,1./(extrapolOrder+2));
        factor = std::max(0.5,std::min(factor,1.33));
        if (verbosity > 0)
        {
          std::cout << "t=" << eq.time() << ", dt=" << dt << ", err=" << err << ", factor=" << factor <<
                       ", red=" << red << ", dof=" << variableSet.degreesOfFreedom() << '\n';
        };
      }
      ++red;
    } while(err>1 && red<=redMax);

    if (verbosity > 0)
    {
      std::cout.flush();
      std::cout << "t= " << eq.time() << ", dt = " << dt << ", factor = " << factor << ", red=" << red << '\n';
    };

    // don't forget to write first value!
    if (eq.time() == 0)
    {
      sampleOut << std::to_string(eq.time()) << ' '  << ' '  << component<0>(x).value(samplePos)[0] << '\n';
    }

    // step ahead
    x += dx;
    eq.setTime(eq.time()+dt);
    dt = std::min(dt*factor,dtMax);

    // write gnu output at sample position
    sampleOut << std::to_string(eq.time()) << ' '  << ' '  << component<0>(x).value(samplePos)[0] << '\n';


    // // perform mesh coarsening
    // std::vector<bool> dummy(0);
    // coarsening(variableSet,x,eq.scaling(),tolX,gridManager,dummy,verbosity);

  }
  std::cout << '\n';

  limex.reportTime(std::cout);

  if (!done)
    std::cout << "*** maxSteps reached ***\n";

  return x; // return current iterate
}

#endif

Results

Some of these results are generated directly within this tutorial example, while further results are provided to show different aspects of the solution, the behavior of the integration methods and the evolution of errors during the calculation. All of the data for these results was generated without modifying the code of this example.

The moving source as 2D heat map over the unit square: movingsource.gif 3D representation of the solution at end time T: movingsource_T.png Evaluation of temperatures at a specific sample position within the unit square for semi-implicit Euler with basic stepsize dt = 0.05 and LIMEX with dt = 0.025: samplepos1.png Evaluation of temperatures at a specific sample position within the unit square for semi-implicit Euler with decreasing basic stepsizes vs. LIMEX: samplepos2.png

What else could be interesting for you to be visualized as output? How would you generate these outputs?

Possibilities for extension


Page last modified: 2026-11-10