Simple Example - Poisson's equation

Create a program that formulates the Poisson equation and specifies the details for Kaskade 7 to find the solution. The complete source code is in tutorial/laplacian/ in the Kaskade 7 repository.

Problem Formulation

Consider the following problem where we search for \(u(x,y)\) that satisfies the 2D Poisson equation \[ -\Delta u = -\nabla \cdot ( \nabla u ) = f \quad\text{ in } \Omega, \qquad u = 0 \quad\text{ on } \partial\Omega, \] where \(\Omega\) denotes the open unit square. The right-hand side is chosen such that the exact solution is known: \[ u(x,y) = x(1-x),y(1-y), \qquad f(x,y) = -\Delta u(x,y) = 2\bigl(x(1-x) + y(1-y)\bigr). \] This is the method of manufactured solutions: it lets us verify the computed solution against an exact one.

Define \[ F(u) := \frac{1}{2}\nabla u^T\nabla u - fu \quad\text{ in } \Omega, \qquad G(u) := \frac{\gamma}{2} h_F^{-2} u^2 \quad\text{ on } \partial\Omega. \] Here, \(\gamma\) is a large penalty parameter for the homogeneous Dirichlet boundary condition and \(h_F\) is the diameter of the current boundary face. Then the Poisson equation is equivalent to the minimization problem \[ \min_{u \in H^1(\Omega)} J(u) = \int_\Omega F(u), dx + \int_{\partial\Omega} G(u) ,dS. \] The penalty term approximates the Dirichlet condition \(u=0\) by penalizing deviations from zero on the boundary. The class DirichletPenaltyBoundary used below additionally scales the penalty with the inverse face measure, such that the method remains accurate under mesh refinement.

Makefile Preparation

In this tutorial we create a program named laplace.cpp and a header file named laplace.hh. In the terminal, begin by creating a directory and a makefile:

mkdir poisson
cd poisson
touch Makefile

The following is a simple makefile for the purpose of this tutorial. The first include line points to Makefile.Local in the Kaskade 7 installation directory (in the container: /kaskade7/Makefile.Local).

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

# Append to FLAGS; Makefile.Local already defines the language and platform flags.
FLAGS += -g -Wall

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

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

Grid and Variable Set Initialization

We begin by defining a grid for our domain and the variable \(u\) on that domain. The main compilation unit laplace.cpp starts as follows. The file laplace.hh containing the variational functional is discussed in the next section.

#include <algorithm>
#include <iostream>

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

#include "fem/assemble.hh"
#include "fem/istlinterface.hh"
#include "fem/functional_aux.hh"
#include "fem/gridmanager.hh"
#include "fem/spaces.hh"                // convenient definition of the H1 space
#include "fem/variables.hh"

#include "io/vtk.hh"
#include "linalg/direct.hh"
#include "utilities/gridGeneration.hh"  // for grid generation (unit square)
#include "utilities/kaskopt.hh"         // for command line option parsing

using namespace Kaskade;
#include "laplace.hh"

int main(int argc, char* argv[])
{
  constexpr int dim = 2;
  int refinements, order;
  double penalty;

  // Kaskade 7 provides a convenient way to parse command line arguments, with
  // defaults provided for each option.
  if (getKaskadeOptions(argc,argv,Options
  ("refine", refinements,           5,"uniform mesh refinements")
  ("order",        order,           2,"polynomial ansatz order")
  ("penalty",    penalty,         1e6,"penalty factor for the Dirichlet boundary conditions")
  )) return 0;

  // Type definitions for the grid, the finite element space, and the variable set.
  using Grid = Dune::UGGrid<dim>;                            // Dune grid on unstructured meshes
  using H1Space = Kaskade::H1Space<Grid>;                    // H1-conforming Lagrange space
  using Spaces = boost::fusion::vector<H1Space const*>;      // tuple of all involved spaces

  // One scalar variable "u" living on the first (0-th) space.
  using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>>>;
  using VariableSetDesc = VariableSetDescription<Spaces,VariableDescriptions>;
  using Functional = PoissonFunctional<double,VariableSetDesc>;

  // The assembler builds the discrete (Galerkin) representation of the
  // functional's linearization: the stiffness matrix and the right hand side.
  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;

  // Grid generation and refinement. createUnitSquare() provides a triangulation of
  // the unit square, globalRefine() refines it uniformly.
  GridManager<Grid> gridManager( createUnitSquare<Grid>() );
  gridManager.globalRefine(refinements);

  // The finite element space of continuous, piecewise polynomial functions of the
  // given polynomial order, on the leaf grid view.
  H1Space h1Space(gridManager,gridManager.grid().leafGridView(),order);
  Spaces spaces(&h1Space);
  VariableSetDesc variableSetDesc(spaces,{ "u" });           // variable set with one variable "u"

  // The energy functional with the given boundary penalty factor.
  Functional F(penalty);

  // The initial guess u = 0.
  auto u = variableSetDesc.variableSet();

  // Optional: visualize the grid and the initial variable.
  writeVTK(u,"temperature_initial",IoOptions().setOrder(order).setPrecision(7));
  std::cout << "Grid and initial variable defined" << std::endl;
}

In the first part we state the dimension of the grid type we will use. We create the unit square grid with createUnitSquare<Grid>() from gridGeneration.hh, which is passed to and wrapped in a GridManager. Grid managers take care of the internal complications so that grid refinement can be performed easily and consistently.

using Grid = Dune::UGGrid<dim>;
GridManager<Grid> gridManager( createUnitSquare<Grid>() );
gridManager.globalRefine(refinements);

The convenience alias Kaskade::H1Space<Grid> denotes a finite element space of globally continuous, piecewise polynomial functions on the leaf grid view of Grid. A leaf grid view (as opposed to a level grid view) is adopted here. A continuous Lagrange mapper manages the degrees of freedom of this space. Here order specifies the degree of the Ansatz polynomials.

using H1Space = Kaskade::H1Space<Grid>;
H1Space h1Space(gridManager,gridManager.grid().leafGridView(),order);

Sometimes we might consider more than one function in the solver. In general we will need to pass a Boost fusion vector of function spaces when we apply the later steps in the solver.

using Spaces = boost::fusion::vector<H1Space const*>;
Spaces spaces(&h1Space);

To specify the function variable we need for the problem, we define the type VariableSetDescription, which links the type of function spaces (a vector) and a vector of variables. When we define the variable vector type, called VariableDescriptions here, we need to specify each variable’s space index and number of components. Space index defines the order in which we arrange the variables and should range from \(0\) to \(n-1\), where \(n\) is the number of variables under consideration. Component refers to the dimension of the output of the functional variable, which should be one unless vector functions are considered. We also use a string "u" to name the variable, which will be important when we need to identify the values in the results.

using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>>>;
using VariableSetDesc = VariableSetDescription<Spaces,VariableDescriptions>;
VariableSetDesc variableSetDesc(spaces,{ "u" });
auto u = variableSetDesc.variableSet();

Visualization of the Grid Using ParaView

The initial program outputs the variable u as a VTK file without performing any calculation. We can visualize the grid using software like ParaView. First create the dependency file, then compile the program:

make laplace.d
make laplace

The first command is required: the Kaskade build rules compile a source file with the correct include paths only after the matching .d file exists. Without it, make laplace falls back to the built-in rule and fails with fem/assemble.hh: No such file or directory.

To execute the script, use

./laplace

After this we should find the file temperature_initial.vtu. In ParaView, a unit square with a value of zero should be observable once the file is loaded.

Initial grid

When there is more than one variable, it is possible to choose another variable in the drop-down menu:

Choose variable

It is also possible to view the grid with the grid lines:

View grid lines

Numerical Evaluation of the Solution of Poisson’s Equation

The following piece of code is appended within main() after the initial output. It assembles the linear system, solves it, adds the Newton step to the initial guess, verifies the result against the exact solution, and writes the final VTK output.

The first listing above already contains the closing brace } of main(). When you append the following block, delete that brace and place the block before the end of main(); otherwise the second part ends up outside the function.

  // Assembly: compute the Galerkin representation of the functional's
  // linearization at the initial guess u=0. For the quadratic energy functional J
  // this is the linear system A x = -F'(0), where A is the (penalized) stiffness
  // matrix and F'(0) = -b is the residual at 0.
  Assembler assembler(variableSetDesc.spaces);
  assembler.assemble(linearization(F,u));

  // The assembled system matrix A (wrapped as a linear operator).
  AssembledGalerkinOperator<Assembler> A(assembler);

  // We compute the Newton step x = -A^{-1} F'(0). The solution coefficients are
  // accumulated in "solution" (starting from zero) via solution += -1 * A^{-1} * rhs.
  auto solution = variableSetDesc.zeroCoefficientVector();
  auto rhs = assembler.rhs();                                // rhs = F'(0)
  auto Ainv = directInverseOperator(A,DirectType::CHOLMOD,
                                    FactorizationOptions(MatrixProperties::POSITIVEDEFINITE));
  Ainv.applyscaleadd(-1.0,rhs,solution);

  // Add the Newton step to the initial guess u=0 to obtain the discrete solution.
  component<0>(u) += component<0>(solution);

  // Verification: compare the computed solution with the known exact solution
  // u(x,y) = x(1-x)y(1-y) at all vertices of the grid.
  double maxError = 0.0;
  for (auto const& v : Dune::vertices(gridManager.grid().leafGridView()))
  {
    Dune::FieldVector<double,dim> x = v.geometry().center();
    double uExact = x[0]*(1-x[0]) * x[1]*(1-x[1]);
    maxError = std::max(maxError, std::abs(component<0>(u).value(x)[0] - uExact));
  }
  std::cout << "maximum pointwise error at vertices: " << maxError << '\n';

  // The solution is written to a VTK file for visualization.
  writeVTK(u,"temperature",IoOptions().setOrder(order).setPrecision(7));

  std::cout << "graphical output finished, data in VTK format is written into file temperature.vtu \n";

The matrix A is symmetric positive definite, so CHOLMOD (a sparse Cholesky factorization from SuiteSparse) is a natural choice. UMFPACK or MUMPS work as well; replace DirectType::CHOLMOD and the matrix properties accordingly. See Direct Solvers for details.

Defining the Variational Functional Class

A variational functional class named PoissonFunctional is written in the header file laplace.hh. It contains the following variables and structures:

Variables/Function Purpose
DomainCache Evaluation of \(F\) (in the domain) and its derivatives
BoundaryCache Evaluation of \(G\) (on the boundary) and its derivatives
D1 Specification of block structures related to the first derivatives
D2 Specification of block structures related to the second derivatives
integrationOrder() Specification of the quadrature order required by the assembler

In particular, DomainCache and BoundaryCache are important class objects with the following members:

Variables/Functions Purpose (for DomainCache)
moveTo() Fix the values that are constant within an entity (such as a cell)
evaluateAt() Fix the values that are constant at a point in the domain
d0() Evaluate the value of \(F\) at the specified point
d1() Evaluate the first directional derivative \(F’\)
d2() Evaluate the second directional derivative \(F’’\)

Efficient computation is achieved by isolating the retrieval of certain values associated with a point. The computations in d0, d1, and d2 use the values computed in evaluateAt().

The following is the laplace.hh used for this tutorial.

#ifndef LAPLACE_HH
#define LAPLACE_HH

#include <algorithm>

#include "fem/diffops/boundaryConditions.hh"   // for DirichletPenaltyBoundary
#include "fem/functional_aux.hh"
#include "fem/fixdune.hh"
#include "fem/gridBasics.hh"
#include "fem/variables.hh"

// The energy functional of the Poisson problem
//     -div(grad u) = f          in Omega = (0,1)^2,
//               u = 0           on dOmega,
// with f = 2[x(1-x)+y(1-y)] and exact solution u(x,y) = x(1-x)y(1-y).
template <class RealType, class VarSetDesc>
class PoissonFunctional: public Kaskade::FunctionalBase<Kaskade::VariationalFunctional>
{
  static_assert(VarSetDesc::noOfVariables==1,"Poisson problem only defined for a single variable.\n");

public:
  using Scalar = RealType;
  using OriginVars = VarSetDesc;
  using AnsatzVars = VarSetDesc;
  using TestVars = VarSetDesc;
  using Grid = typename AnsatzVars::Grid;
  using GridView = typename AnsatzVars::GridView;
  using Cell = Kaskade::Cell<Grid>;

  static constexpr int dim = AnsatzVars::Grid::dimension;
  static constexpr int uIdx = 0;
  static constexpr int uSpaceIdx = Kaskade::spaceIndex<AnsatzVars,uIdx>;

  // F(x,u,grad u) = 1/2 |grad u|^2 - f(x) u on a cell.
  class DomainCache: public Kaskade::CacheBase<PoissonFunctional,DomainCache>
  {
  public:
    DomainCache(PoissonFunctional const&,
                typename OriginVars::VariableSet const& vars_,
                int flags=7):
      vars(vars_)
    {}

    void moveTo(Cell const& c)
    {
      cell = c;
    }

    template <class Evaluators>
    void evaluateAt(Kaskade::LocalPosition<Grid> const& xi, Evaluators const& evaluators)
    {
      u  = vars.template value<uIdx>(evaluators);
      du = vars.template derivative<uIdx>(evaluators)[0];

      auto x = cell.geometry().global(xi);
      f = 2*(x[0]*(1-x[0]) + x[1]*(1-x[1]));
    }

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

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

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

  private:
    typename OriginVars::VariableSet const& vars;
    Cell cell;
    Dune::FieldVector<Scalar,1> u, f;
    Dune::FieldVector<Scalar,dim> du;
  };

  // G(x,u) = 1/2 gamma h_F^{-2} (u-u_D)^2 on a boundary face.
  class BoundaryCache
  {
  public:
    BoundaryCache(PoissonFunctional<RealType,AnsatzVars> const& functional,
                  typename OriginVars::VariableSet const& vars_,
                  int flags=7):
      vars(vars_), penalty(functional.penalty), uDirichletBoundaryValue(0.0)
    {}

    template <class FaceIterator>
    void moveTo(FaceIterator const& fi)
    {
      dirichlet.moveTo(fi);
    }

    template <class Evaluators>
    void evaluateAt(Kaskade::FaceLocalPosition<GridView> const& xi, Evaluators const& evaluators)
    {
      auto u = vars.template value<uIdx>(evaluators);
      dirichlet.setBoundaryData(penalty,u,uDirichletBoundaryValue);
    }

    Scalar d0() const
    {
      return dirichlet.d0();
    }

    template<int row>
    Kaskade::D1Result<TestVars,row> d1(Kaskade::VariationalArg<Scalar,dim> const& argT) const
    {
      return dirichlet.d1(argT);
    }

    template<int row, int col>
    Kaskade::D2Result<TestVars,row,AnsatzVars,col>
    d2(Kaskade::VariationalArg<Scalar,dim> const& argT,
       Kaskade::VariationalArg<Scalar,dim> const& argA) const
    {
      return dirichlet.d2(argT,argA);
    }

  private:
    typename OriginVars::VariableSet const& vars;
    Scalar penalty;
    Dune::FieldVector<Scalar,1> uDirichletBoundaryValue;
    Kaskade::DirichletPenaltyBoundary<typename AnsatzVars::GridView,1> dirichlet;
  };

  template <int row>
  struct D1: public Kaskade::FunctionalBase<Kaskade::VariationalFunctional>::D1<row>
  { };

  template <int row, int col>
  struct D2: public Kaskade::FunctionalBase<Kaskade::VariationalFunctional>::D2<row,col>
  { };

  PoissonFunctional(double gamma=1e6)
  : penalty(gamma)
  {}

  // The quadrature order is chosen such that the integrands are integrated
  // exactly: |grad u|^2 has degree 2(order-1), f u has degree 2*order, and the
  // boundary penalty (u-u_D)^2 has degree 2*order.
  template <class Cell>
  int integrationOrder(Cell const& /* cell */, int shapeFunctionOrder, bool boundary) const
  {
    if (boundary)
      return 2*shapeFunctionOrder;
    else
    {
      int stiffnessMatrixIntegrationOrder = 2*(shapeFunctionOrder-1);
      int sourceTermIntegrationOrder = 2*shapeFunctionOrder;

      return std::max(stiffnessMatrixIntegrationOrder,sourceTermIntegrationOrder);
    }
  }

private:
  double penalty;
};

#endif

DomainCache objects are created once per thread and queried in parallel during assembly. They must therefore be thread-safe and may not modify shared state, in particular not the functional object itself.


Page last modified: 2026-11-10