Variational formulations for elliptic problems require the specification of the functions \( F \) and \( G \) as outlined in the basics. This is done by writing a class that adheres to the NonlinearVariationalFunctional concept, see the Doxygen documentation. In the following, we go through the essential components of such a class.
The first ingredient is to specify whether this is a symmetric problem with a variational functional (like the Poisson equation) or just a weak formulation (like advection–diffusion equations). This is most conveniently done by deriving from the base class FunctionalBase, which accepts the problem type as a template parameter: the enum values VariationalFunctional and WeakFormulation can be used.
In addition, the scalar field type (usually double, but could also be float, complex, or an automatic-differentiation-augmented type) must be announced.
class Functional: public Kaskade::FunctionalBase<Kaskade::VariationalFunctional>
{
public:
using Scalar = double;
The type of the grid is usually taken from the variable set description; the tutorial functionals additionally define a few convenience aliases:
using Grid = typename AnsatzVars::Grid;
using GridView = typename AnsatzVars::GridView;
using Cell = Kaskade::Cell<Grid>;
Next, the number and type of variables and test functions. For systems such as Stokes flow or KKT systems in optimal control, there are multiple variables coming from different function spaces, which need to be specified statically by providing a VariableSetDescription<...> type — containing a static list of variables, their number of components, and the index of the space they belong to. This is often passed as a template parameter to the class we define, so that the finite element spaces can easily be configured from outside. For symmetric problems, ansatz and test variables are the same, but for nonsymmetric weak formulations they may be different.
Moreover, for nonlinear problems one may want to provide a linearization point of the equations that is not contained in the ansatz space (e.g., an analytically given approximation), and then compute a correction (Newton step) in the ansatz space. Therefore, the type of variables used to describe this linearization point has to be given as well — most often it is just the type of the ansatz variables itself.
using OriginVars = VarSetDesc; // space of the linearization point
using AnsatzVars = VarSetDesc; // space of the Newton correction
using TestVars = VarSetDesc; // space of the test functions
Then the functions \( F \) and \( G \) need to be defined, including their derivatives. This is done by defining a member class for each of these two functions, the DomainCache for \( F \) and the BoundaryCache for \( G \).
These mainly define the function values (zeroth-order derivative, method d0, only for variational problems), and first and second order directional derivatives (methods d1 and d2, respectively). These classes are instantiated multiple times for multi-threaded assembly of the stiffness matrix and right hand side, and must therefore be thread-safe.
A convenient way to obtain do-nothing defaults for moveTo, evaluateAt, and zero defaults for d0, d1, d2 is to derive the cache from CacheBase:
class DomainCache: public Kaskade::CacheBase<Functional,DomainCache>
{
public:
CacheBase also handles the conversion between scalar and multi-component VariationalArg objects. For simple scalar problems it is equally fine to implement d1 and d2 directly, as the Poisson tutorial does.
The caches are constructed by the assembler (or by the convenience helper function linearization(F,u)) using a particular constructor convention. The variational functional object F is provided, as well as the linearization point \( u \) and a bitfield of flags announcing which subset of the three values shall be computed — the matrix (d2), the right hand side (d1), or the value of the functional (d0).
DomainCache(Functional const& F,
typename OriginVars::VariableSet const& u,
int flags);
For evaluating the integrals outlined in the basics, the function \( F \) must be evaluated at a position \( x \in \Omega \), which is provided in two steps — as the grid cell \( T \) in which the point lies, and its cell-local coordinate \( \xi \in T \). This two-step procedure is done for performance reasons, since some computations such as index look-ups need to be done only once for each cell, and not again for each quadrature point. In addition, again for performance reasons, an object eval is provided that already contains shape functions evaluated at the given local position and can be used for efficient evaluation of the linearization point variables.
void moveTo(Cell const& cell);
void evaluateAt(LocalPosition const& xi, Evaluators const& eval);
Then the actual function and derivative evaluations need to be provided. For the variational functional value \( J(u) \) this is simple, as it only depends on the linearization point \( u \) given at DomainCache construction.
Scalar d0() const;
The derivatives are directional derivatives in the given direction, for which value and spatial derivative are provided in a VariationalArg object. The direction is specified for a particular variable identified by its number, i.e. the row number for test variables and column number for ansatz variables. Row and column are specified statically as template parameters.
template <int row>
D1Result<TestVars,row> // a vector type
d1(VariationalArg<Scalar,dim> const& argT) const;
template <int row, int col>
D2Result<TestVars,row,
AnsatzVars,col> // a matrix type
d2(VariationalArg<Scalar,dim> const& argT,
VariationalArg<Scalar,dim> const& argA) const;
};
The aliases D1Result and D2Result expand to a Dune::FieldVector and a Dune::FieldMatrix, respectively, with the number of components of the involved variables. They avoid spelling out the component counts by hand.
The return type deserves some explanation. For multiple-component variables such as displacement in solid mechanics or velocity in fluid mechanics, the finite element functions are defined in terms of scalar FE function spaces such as the ubiquitous Lagrange spaces. Consequently, the test function \( \phi \) is scalar, with value and derivative provided in argT, whereas conceptually the test function is vectorial with dimension \( m \). Now the \( i \)-th entry of the return vector of d1 shall contain the directional derivative in the direction of the (vectorial) test function \( \phi e_i \), where \( e_i \) is the \( i \)-th unit vector.
For the second derivative, of course, two directions are given, related to the test space and the ansatz space, respectively. The same return value construction as for d1 is used, so that for multi-component variables a matrix is returned.
The BoundaryCache does exactly the same for the function \( G \), with the only exception that instead of a grid cell, a FaceIterator pointing to the current boundary face is provided.
PDEs come in a huge variety, and thus we need to specify some structural information in addition. This is done via the member class templates D1 and D2, parametrized by row (i.e. equation number) and column (i.e. variable number). They express properties of individual blocks of the stiffness matrix, in particular for the case of PDE systems — whether a block is present at all, whether it is symmetric, and whether it shall be lumped.
FunctionalBase already provides safe defaults, so in the simplest case these classes can simply inherit from them:
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>
{ };
Override individual flags only where the default is too conservative. For example, a symmetric diagonal block of a variational problem can be declared explicitly as follows:
template <int row, int col>
struct D2: public Kaskade::FunctionalBase<Kaskade::VariationalFunctional>::D2<row,col>
{
static constexpr bool present = true;
static constexpr bool symmetric = true;
static constexpr bool lumped = false;
};
The defaults are: present is true for all blocks of a weak formulation and for the lower triangle (including the diagonal) of a variational functional; symmetric is true for diagonal blocks of a variational functional. Non-present blocks are not assembled at all, and the assembly of symmetric blocks is more efficient than that of nonsymmetric blocks. Further flags include lumped (assemble only the diagonal, mainly for hierarchical error estimators) and makePositive (project local matrices onto the positive semidefinite cone during nonconvex minimization). The D1 block information additionally contains a derivatives field.
For the corresponding D1, parametrized only by row, in particular the presence of right hand side blocks is of interest.
Finally, we need to specify which quadrature order shall be used on any grid cell or boundary face, given the polynomial order of the shape functions. FunctionalBase defaults to twice the shape function order; override this method if the integrands require a different order.
int integrationOrder(Cell const& cell,
int shapeFunctionOrder,
bool boundary) const;
};
Have a look at the tutorial section for more insights into the implementation of different types of problems.
Boundary conditions are implemented in the BoundaryCache. The following example switches between a Nitsche and a penalty formulation, depending on which part of the boundary is currently processed:
template <class FaceIterator>
void moveTo(FaceIterator const& fi)
{
useNitsche = fi->centerUnitOuterNormal()[0] > 0.5;
if (useNitsche)
nitsche.moveTo(fi);
else
dirichlet.moveTo(fi);
}
template <class Position, class Evaluators>
void evaluateAt(Position const& xi, Evaluators const& evaluators)
{
auto u = vars.template value<uIdx>(evaluators);
if (useNitsche)
{
auto ux = vars.template derivative<uIdx>(evaluators);
nitsche.setBoundaryData(xi,penalty,u,uDirichletBoundaryValue,ux,unitMatrix<Scalar,dim>());
}
else
dirichlet.setBoundaryData(penalty,u,uDirichletBoundaryValue);
}
Scalar d0() const
{
if (useNitsche)
return nitsche.d0();
else
return dirichlet.d0();
}
template<int row>
Dune::FieldVector<Scalar,1> d1(Kaskade::VariationalArg<Scalar,dim> const& argT) const
{
if (useNitsche)
return nitsche.d1(argT);
else
return dirichlet.d1(argT);
}
template<int row, int col>
Dune::FieldMatrix<Scalar,1,1> d2(Kaskade::VariationalArg<Scalar,dim> const &argT,
Kaskade::VariationalArg<Scalar,dim> const &argA) const
{
if (useNitsche)
return nitsche.d2(argT,argA);
else
return dirichlet.d2(argT,argA);
}
Kaskade 7 provides the corresponding helper classes in fem/diffops/boundaryConditions.hh:
DirichletPenaltyBoundary<typename AnsatzVars::GridView,1> dirichlet;
DirichletNitscheBoundary<typename AnsatzVars::GridView,1> nitsche;
The penalty variant realizes \( \frac{\gamma}{2} h_F^{-2}|u-u_D|^2 \) on the boundary and is simple to use, but the factor \( h_F^{-2} \) can lead to ill-conditioned stiffness matrices under mesh refinement. The Nitsche variant realizes \( \frac{\gamma}{2} h_F^{-1}|u-u_D|^2 - u^\top u_x \kappa n \), avoids this deterioration of the condition number, and requires the normal derivative and the diffusivity tensor in setBoundaryData. Both classes scale the penalty with the face diameter internally; gamma is the user-supplied penalty parameter.