Inverse Problems

This example illustrates:

  • Systems of PDEs
  • Accessing matrix blocks for block solver
  • Writing multiple outputs
  • Passing a measurement field during assembly

and can be found at tutorial/inverse.

Background

This tutorial considers the source term inversion of an elliptic problem by identifying the volume source term \(f\) which produces the temperature field \(T\). Synthetic measurement data is produced by the same numerical scheme as used for the inversion. Since this is considered an inverse crime, noise is added to the measurement data. The method of Lagrange multipliers is used to enforce the equality constraint of satisfying the state PDE. Since inverse problems are inherently ill-posed, a Tikhonov regularization scheme is employed.

Mathematical Formulation

Given an open bounded domain \(\Omega \subset \mathbb{R}^d\), \(d \in {1,2}\), consider the following least-squares functional: \[ \min_ {f} J(f,T) = \frac{1}{2}\int_\Omega (T-T_m)^2 ,d\Omega + \frac{\alpha}{2}\int _{\Omega} |\nabla f|^2 ,d \Omega . \] Here \( T_m \) is the measured temperature field, the second term is the \(H^1\) Tikhonov regularization term with regularization parameter \( \alpha \), and \( T \) is the solution of the elliptic state equation \[ -\nabla \cdot (\kappa \nabla T) + qT = f \quad \text{in } \Omega, \] with the boundary conditions \[ \kappa \nabla T \cdot n = 0 \quad \text{on }\Gamma_N \subset \partial\Omega, \qquad T = g \quad \text{on } \Gamma_D \subset \partial\Omega. \]

To enforce the state equation as an equality constraint, we introduce the Lagrange multiplier function \( \lambda \) and obtain the Lagrange functional \[ \mathcal{L} (T,\lambda,f) := \frac{1}{2}\int_\Omega (T-T_m)^2 ,d\Omega

  • \frac{\alpha}{2}\int _{\Omega} |\nabla f|^2 ,d \Omega
  • \int {\Omega} \lambda \bigl(-\nabla \cdot (\kappa \nabla T) + qT - f\bigr) ,d \Omega . \] After integration by parts (assuming that \(\lambda\) vanishes on the Dirichlet boundary), the constraint term becomes \[ \int\Omega \bigl(\kappa \nabla T \cdot \nabla \lambda + qT\lambda - f\lambda\bigr),d\Omega . \]

The necessary optimality conditions require that the variations of \(\mathcal{L}\) with respect to \(T\), \(\lambda\), and \(f\) vanish: \[ \begin{aligned} \mathcal{L}{\lambda}(T,\lambda,f)(\delta \lambda) &= \int\Omega \bigl(\kappa \nabla T \cdot \nabla \delta\lambda + qT,\delta \lambda - f,\delta \lambda\bigr),d\Omega = 0, \\ \mathcal{L}{T}(T,\lambda,f)(\delta T) &= \int\Omega \bigl((T-T_m)\delta T + \kappa \nabla \delta T \cdot \nabla \lambda + q,\delta T,\lambda\bigr),d\Omega = 0, \\ \mathcal{L}{f}(T,\lambda,f)(\delta f) &= \int\Omega \bigl(\alpha \nabla f \cdot \nabla \delta f - \lambda,\delta f\bigr),d\Omega = 0. \end{aligned} \] These are the weak forms of the state, adjoint, and control equations, respectively. The corresponding strong forms are \[ -\nabla \cdot (\kappa \nabla T) + qT = f \quad \text{in } \Omega, \] \[ T - T_m - \nabla \cdot (\kappa \nabla \lambda) + q\lambda = 0 \quad \text{in } \Omega, \] \[ -\alpha \Delta f - \lambda = 0 \quad \text{in } \Omega, \] together with the natural boundary conditions \(\kappa \nabla T \cdot n = 0\), \(\kappa \nabla \lambda \cdot n = 0\), and \(\alpha \nabla f \cdot n = 0\) on the Neumann part of the boundary.

In this tutorial \(\kappa\) is a positive scalar constant. The weak forms remain valid for a symmetric tensor-valued \(\kappa\); in the adjoint strong form \(\nabla\cdot(\kappa\nabla\lambda)\) then has to be read as \(\nabla\cdot(\kappa^T\nabla\lambda)\).

It is helpful for later on in the implementation to formulate the strong form as

\[ \begin{bmatrix} I&-\nabla\cdot(\kappa\nabla)+q&0 \\ -\nabla\cdot(\kappa\nabla)+q&0&-I \\ 0&-I&-\alpha \Delta \end{bmatrix} \begin{bmatrix} T \\ \lambda \\ f \end{bmatrix} = \begin{bmatrix} T_{m} \\ 0 \\ 0 \end{bmatrix} \]

Discretization

By employing a Galerkin discretization to the system of Lagrange optimality conditions, the discretized system of equations will be

\[ \begin{bmatrix} A_{T}&K_{\lambda} + q A_{\lambda}&0 \\ K_{T} + q A_{T}&0&-A_{f} \\ 0&-A_{\lambda}&\alpha K_{f} \end{bmatrix} \begin{bmatrix} T \\ \lambda \\ f \end{bmatrix} = \begin{bmatrix} b_m \\ 0 \\ 0 \end{bmatrix} \]

Here \(A\) and \(K\) denote mass and stiffness matrices, and \(b_m\) is the vector with entries \(\int_\Omega T_m \varphi_i,d\Omega\). Since \(T\), \(\lambda\), and \(f\) can be discretized with different ansatz functions and discretization orders, the resulting mass and stiffness matrices can differ for each variable; hence the subscripts.

Source code documentation

In this problem the code can be divided into two parts, measurement generation and source inversion, with three files of interest: ht.hh, inverse.hh, and inverse.cpp.

I. Measurement generation

To generate the measurement temperature field we first solve the state equation for \(T\): \[ -\nabla \cdot (\kappa \nabla T) + qT = f \quad \text{in } \Omega, \] with homogeneous Dirichlet boundary conditions: \[ T =0 \quad \text{on } \Gamma_D = \partial\Omega. \]

Given a distributed source term f = 10^5 over the interval:

\[ f(x,y) = \begin{cases} 10^5, & 0.25<x< 0.75 \; \wedge \; 0.25<y<0.75 \\ 0, & \text{otherwise} \end{cases} \]

The relevant part is the first block of inverse.cpp together with ht.hh.

Include header files :

#include <iostream>
#include <string>
#include <random>

#include <boost/timer/timer.hpp>

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

#include "fem/assemble.hh"
#include "fem/norms.hh"
#include "fem/lagrangespace.hh"
#include "linalg/direct.hh"
#include "utilities/enums.hh"
#include "utilities/gridGeneration.hh" //  createUnitSquare
#include "io/vtk.hh"
#include "utilities/kaskopt.hh"

#include "ht.hh"
#include "inverse.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)

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

Build and run with

make inverse.d
make inverse
./inverse --refinements 4

The dependency file must be generated first; see the Hello World section for the reason.

Command line input parameters : Here we can define default parameters for the problem which can be changed from the command line when running the executable .e.g (./inverse - -refinements 4) will refine the mesh 4 times instead of the default value 5. This is useful since the program needs to be compiled once.

int main(int argc, char* argv[])
{
  using namespace boost::fusion;

  int verbosityOpt = 1;
  bool dump = false;

  std::unique_ptr<boost::property_tree::ptree> pt = getKaskadeOptions(argc, argv, verbosityOpt, dump);

  int  refinements = getParameter(pt, "refinements", 5), // Number of times the mesh is refined
       order       = getParameter(pt, "order", 1); // Discretization order

  double   kappa   = getParameter(pt, "kappa", 1.0), //The diffusion constant
           q       = getParameter(pt, "q", 1.0), //The mass coefficient
	       alpha   = getParameter(pt,"alpha",1e-6), //The regularization parameter
	       noise   = getParameter(pt,"noise",1); //Standard deviation of the added noise

Grid creation and Space definition is similar to section Hello world, with the exception of adding a Discontinuous Lagrange space for storing the source term and passing the measurement term to the inverse problem formulation in the next section.

Spaces now contain a ContinuousLagrangeMapper type H1 Space and a DiscontinuousLagrangeMapper type L2 Space, with a corresponding Space index of <0> and <1>.

  constexpr int dim=2;
  using Grid = Dune::UGGrid<dim>;
  using LeafView = Grid::LeafGridView;
  using H1Space  = FEFunctionSpace<ContinuousLagrangeMapper<double,LeafView> >;

  using L2Space  = FEFunctionSpace<DiscontinuousLagrangeMapper<double,LeafView>>; // New Space definition
  using Spaces   = boost::fusion::vector<H1Space const*, L2Space const*>;         // Combined H1 and L2 Space

  using VariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0> > >;
  using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;
  using Functional = HeatFunctional<double,VariableSet>;
  using Assembler = VariationalFunctionalAssembler<LinearizationAt<Functional> >;

  // Geometry creation and mesh refinement.
  GridManager<Grid> gridManager(createUnitSquare<Grid>());
  gridManager.globalRefine(refinements);

Next we create a L2Space::Element_t<1> object this space can be used for storing values inside each cell in the meshed domain, the template parameter is for the number of values to be stored in each cell in this case it is 1.

note: The order in the created l2Space is set to 0, with this we can store a constant value in the cells.

  // construction of finite element space for the scalar solution T_m.
  H1Space h1Space(gridManager,gridManager.grid().leafGridView(),order);

  L2Space l2Space(gridManager,gridManager.grid().leafGridView(),0);

  Spaces spaces(&h1Space,&l2Space);

  //construction of L2 space with 1 component for storage
  L2Space::Element_t<1> measurement(l2Space);
  L2Space::Element_t<1> sourceSpace(l2Space);

Defining the necessary source term, DomainCache, and BoundaryCache is similar to Timestepping, but in this problem we have an extra mass term in the DomainCache. All of these are defined in the header file ht.hh.

Here using the evaluateAt member function we can define the source term f

 void evaluateAt(LocalPosition<Grid> const& x, Evaluators const& evaluators)
    {
      u  = data.template value<0>(evaluators);
      du = data.template derivative<0>(evaluators)[0];

      xglob = cell.geometry().global(x);

      if (xglob[0] >0.25 && xglob[0]<0.75 && xglob[1] >0.25 && xglob[1]<0.75 ){
       f=1e5;
      }
      else f=0.0;
    }

The mathematical form of the member functions d0 , d1 and d2 in theDomainCache

\[ \text{d0: } F(T) = \frac{1}{2}\bigl(\kappa \nabla T \cdot \nabla T + qT^2\bigr) - fT. \] \[ \begin{aligned} &\text{d1: } F’(T)[v] = \kappa \nabla T \cdot \nabla v+ qTv - fv \\ &\text{d2: } F’’(T)[v,w] = \kappa \nabla v \cdot \nabla w + qwv \end{aligned} \]

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

    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.q*u*arg.value - 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 &argT,
        VariationalArg<Scalar,dim> const &argA) const
    {
      return F.kappa*argT.derivative[0]*argA.derivative[0] + F.q*argT.value*argA.value;
    }

Now the forward problem is assembled and solved for \(T_m\):

  std::string varNames[1] = { "T_m" };
  std::string sourceVarNames[1] = { "source" };

  VariableSet variableSet(spaces,varNames);
  VariableSet sourceVariableSet(spaces,sourceVarNames);

  Functional F(kappa,q);

  Assembler assembler(spaces);
  VariableSet::VariableSet T_m(variableSet);
  VariableSet::VariableSet source(sourceVariableSet);

  assembler.assemble(linearization(F,T_m));

  auto rhs      = assembler.rhs();
  auto solution = variableSet.zeroCoefficientVector();
  AssembledGalerkinOperator<Assembler> A(assembler);

  directInverseOperator(A,DirectType::UMFPACK,MatrixProperties::GENERAL)
      .applyscaleadd(-1.0,rhs,solution);
  T_m.data = solution.data;

After solving the state equation using directInverseOperator for the scalar variable \(T\), we have the desired measurement field \(T_m\). Next we add noise to \(T_m\) using std::default_random_engine to generate random numbers and std::normal_distribution to obtain a Gaussian distribution with mean \(T_m\) and standard deviation given by the input parameter noise.

To perform this operation we will make use of the interpolateGlobally, it interpolates values from one function space element to another by traversing each cell in the function space using makeFunctionView and takes a weighing scheme as a template parameter. In this problem we interpolate values from the solution space \(T_m\) which is an H1 continuous Lagrange space to our measurement which is a L2 discontinuous Lagrange space.

  // create a random number generator
  std::default_random_engine generator;


  interpolateGlobally<PlainAverage>(measurement,makeFunctionView(h1Space, [&] (auto const& evaluator)
  {

    double m = component<0>(T_m).value(evaluator) ;
    std::normal_distribution<double> distribution(m,noise);


    return Dune::FieldVector<double,1>( distribution(generator));

  }));

Now we have the noisy measurements stored, to visualize the resulting source term we can make use again of interpolateGlobally to store its values.


  //Storing the source field for visualization

  interpolateGlobally<PlainAverage>(sourceSpace,makeFunctionView(h1Space, [&] (auto const& evaluator)
  {

    auto   x = evaluator.cell().geometry().center();
    double f=0;

   if (x[0] >0.25 && x[0]<0.75 && x[1] >0.25 && x[1]<0.75 ) f=1e5;

    return Dune::FieldVector<double,1>(f);

  }));

The resulting source distribution is visualized in the output VTU file Source.vtu.

Original_Source.png

The resulting temperature field is in temperature.vtu.

Original_Temp.png

II. Source term identification

For setting up the system of equations we first need to define 3 variables \(T, \lambda, f \) in the VariableDescriptions along with redefining the Classes depending on it VariableSet , Functional and Assembler. Here, the space index for all the variable is set to <0> this means all the variables will be discretized using the \(H1\) continuous Lagrange polynomials of the same order.

Here, one also can choose a different discretization for each variable by creating the desired space and assigning the variable to it.

Note: The capital I is for indicating the inverse problem related definitions.

  using IVariableDescriptions = boost::fusion::vector<Variable<SpaceIndex<0>,Components<1>,VariableId<0>>,
                                                      Variable<SpaceIndex<0>,Components<1>,VariableId<1>>,
                                                      Variable<SpaceIndex<0>,Components<1>,VariableId<2>>>;

  using IVariableSet        = VariableSetDescription<Spaces,IVariableDescriptions>;
  using IFunctional         = IHeatFunctional<double,IVariableSet>;
  using IAssembler          = VariationalFunctionalAssembler<LinearizationAt<IFunctional> >;



  std::string  IvarNames[3] = { "T","lambda","f" };
  IVariableSet IvariableSet(spaces,IvarNames);
  IFunctional  IF(kappa,q,alpha,measurement);

Notice here we passed the regularization parameter \(\alpha \) and the measurement to the functional. To define the DomainCache and BoundaryCache, we move on to the header inverse.hh.

To pass the measurement to the functional we first need its type inside the functional class definition, this is done in the following lines

  using Spaces = typename AnsatzVars::Spaces;
  using MeasurementSpace = std::remove_pointer_t<typename boost::fusion::result_of::value_at_c<Spaces,1>::type>;
  using MeasurementData  = typename MeasurementSpace::template Element_t<1>;

Notice the use of typename boost::fusion::result_of::value_at_c<Spaces,1>::type: the space index is set to 1, which refers to the L2Space created before in Spaces. The alias MeasurementData defines the type necessary to pass the measurement.

In the evaluateAt member function we can retrieve the measurement value at the integration points using boost::fusion::at_c<1>(evaluators), as well as the values of the problem variables.

    template <class Evaluators>
    void evaluateAt(LocalPosition<Grid> const& x, Evaluators const& evaluators)
    {
      T  = data.template value<0>(evaluators);
      dT = data.template derivative<0>(evaluators)[0];

      lambda  = data.template value<1>(evaluators);
      dlambda = data.template derivative<1>(evaluators)[0];

      f  = data.template value<2>(evaluators);
      df = data.template derivative<2>(evaluators)[0];



      alpha= F.alpha;
      T_m   = F.measurementData.value(boost::fusion::at_c<1>(evaluators));

    }

Moving on to the DomainCache, we define the necessary d1(), d2(), and the optional d0(). The function d0() is the Lagrange functional (after integration by parts of the constraint): \[ \text{d0: } F(T,\lambda,f) = \frac{1}{2} (T-T_m)^2 + \frac{\alpha}{2} |\nabla f|^2 + \kappa \nabla T \cdot \nabla \lambda + qT\lambda - f\lambda . \]

    Scalar d0() const
    {
      return (T-T_m)*(T-T_m)/2 + (alpha/2 *df*df) + dT*F.kappa*dlambda + T*F.q*lambda - f*lambda ;
    }

Here in d1(), since we have a system of three equations, we take the first Fréchet derivative of d0() in the direction of the test function \(v_i\) associated with equation \(i\).

\[ \begin{aligned} &\text{d1-1: } F’(T, \lambda , f)[v_1] = (T-T_m)v_1 + \kappa \nabla v_1 \cdot \nabla \lambda +q \lambda v_1 \\ &\text{d1-2: } F’(T, \lambda , f)[v_2] = \kappa \nabla T \cdot \nabla v_2 + qT v_2 - f v_2 \\ &\text{d1-3: } F’(T, \lambda , f)[v_3] = \alpha \nabla f \cdot \nabla v_3 - \lambda v_3\\ \end{aligned} \]

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
    if(row ==0) return (T-T_m)*arg.value + F.kappa*arg.derivative[0] *dlambda + arg.value*F.q*lambda ;
    if(row ==1) return F.kappa*dT*arg.derivative[0] + F.q*T*arg.value - f*arg.value ;
    if(row ==2) return alpha* df * arg.derivative[0] -arg.value*lambda ;

    }

Similarly, for d2() we take the second Fréchet derivative of d0() in the directions of the test function \(v_i\) and the ansatz function \(w_j\). This results in the system of discretized equations from the Discretization section.

For the Adjoint equation :

\[ \begin{aligned} &\text{d2-11: } F’’(T, \lambda , f)[v_1,w1] = v_1 w_1\\ &\text{d2-12: } F’’(T, \lambda , f)[v_1,w_2] = \kappa \nabla v_1 \cdot \nabla w_2 + q v_1 w_2 \\ &\text{d2-13: } F’’(T, \lambda , f)[v_1,w3] = 0 \\ \end{aligned} \]

For the State equation :

\[ \begin{aligned} &\quad \text{d2-21: } F’’(T, \lambda , f)[v_2,w1] = \kappa \nabla v_2 \nabla w_1 + q v_2 w_1\\ &\quad \text{d2-22: } F’’(T, \lambda , f)[v_2,w2] = 0 \\ &\quad \text{d2-23: } F’’(T, \lambda , f)[v_2,w3] = - v_2 w_3 \\ \end{aligned} \]

For the Control equation :

\[ \begin{aligned} &\text{d2-31: } F’’(T, \lambda , f)[v_3,w1] = 0\\ &\text{d2-32: } F’’(T, \lambda , f)[v_3,w2] = - v_3 w_2 \\ &\text{d2-33: } F’’(T, \lambda , f)[v_3,w3] = \alpha \nabla v_3 \nabla w_3 \\ \end{aligned} \]

    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 &argT,
        VariationalArg<Scalar,dim> const &argA) const
    {
     if(row==0 && col ==0) return argA.value *argT.value;
     if(row==0 && col ==1) return F.kappa*argA.derivative[0]*argT.derivative[0] + F.q*argA.value*argT.value;
     if(row==0 && col ==2) return 0;

     if(row==1 && col ==0) return F.kappa*argA.derivative[0]*argT.derivative[0] + F.q *argA.value*argT.value;
     if(row==1 && col ==1) return 0;
     if(row==1 && col ==2) return -argA.value*argT.value;

     if(row==2 && col ==0) return 0;
     if(row==2 && col ==1) return -argA.value*argT.value;
     if(row==2 && col ==2) return alpha* argA.derivative[0]*argT.derivative[0]  ;
    }

The formulas above use the general coefficients \(\kappa\) and \(q\). In the current tutorial source, block (0,1) omits these factors. That is consistent only for the default values \(\kappa=q=1\); for other coefficients the block (0,1) has to include \(\kappa\) and \(q\) as shown above. The KKT matrix itself remains symmetric: block (1,0) contains the same coefficients, and the off-diagonal coupling blocks (1,2) and (2,1) are both \(-1\).

For the BoundaryCache since we have only contribution from the state equation for the boundary term it is similar to Timestepping and since the state equation is placed in the second row of the system of equations, the d0(),d1(),d2() will be as follows

    template <class Evaluators>
    void evaluateAt(Dune::FieldVector<typename Grid::ctype,dim-1> const& x, Evaluators const& evaluators)
    {

      T = data.template value<0>(evaluators);
      lambda = data.template value<1>(evaluators);
      f = data.template value<2>(evaluators);
      T0 = 0;
    }

    Scalar
    d0() const
    {
      return penalty*(T-T0)*(T-T0)/2 ;
    }

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
      if(row==1) return penalty*(T-T0)*arg.value;
      else return 0.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
    {
      if (row==1 && col==0  ) return penalty*arg1.value*arg2.value;
      else return 0.0;
    }

  private:
    typename AnsatzVars::VariableSet const& data;
    FaceIterator const* e;
    Scalar penalty, T, T0, lambda,f;
  };

This linear system of equations can be solved by the directInverseOperator, since it supports block evaluation. the inverseVariables will contain the solution for \(T,\lambda ,f \) and it can be stored in a vtu output file.

  IAssembler Iassembler(spaces);
  IVariableSet::VariableSet inverseVariables(IvariableSet);

  boost::timer::cpu_timer IassembTimer;
  Iassembler.assemble(linearization(IF,inverseVariables));
  std::cout << "computing time for inverse assemble: " << boost::timer::format(IassembTimer.elapsed()) << "\n";


  auto  Irhs      = Iassembler.rhs();
  auto  Isolution = IvariableSet.zeroCoefficientVector();

  boost::timer::cpu_timer IdirectTimer;

  AssembledGalerkinOperator<IAssembler> IA(Iassembler);


  directInverseOperator(IA,DirectType::UMFPACK,MatrixProperties::GENERAL).applyscaleadd(-1.0,Irhs,Isolution);
  inverseVariables.data = Isolution.data;
  std::cout << "computing time for inverse direct solve: " << boost::timer::format(IdirectTimer.elapsed()) << "\n";


  // output of solution in VTK format.

  boost::timer::cpu_timer outputTimer;
  component<0>(source)= sourceSpace;
  writeVTK(inverseVariables,"temperature_inverse",IoOptions().setOrder(order).setPrecision(7));
  writeVTK(T_m,"temperature",IoOptions().setOrder(order).setPrecision(7));
  writeVTK(source,"Source",IoOptions().setOrder(order).setPrecision(7));

  std::cout << "End Inverse tutorial program" << '\n';
  return 0;
}

Complete header files

The fragments above show only the parts that are specific to the inverse problem. The complete headers are required for compilation. They are reproduced here so that the example is self-contained. The listing of inverse.hh below includes the general factors \(\kappa\) and \(q\) in block (0,1), as discussed above; the copy in tutorial/inverse in the Kaskade 7 repository currently omits them.

ht.hh

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

#ifndef HEATTRANSFER_HH
#define HEATTRANSFER_HH

#include <cmath>

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

/// Example stationary heat transfer equation
///

template <class RType, class VarSet>
class HeatFunctional: public FunctionalBase<VariationalFunctional>
{
public:
  using Scalar = RType;
  using OriginVars = VarSet;
  using AnsatzVars = VarSet;
  using TestVars = VarSet;
  using Grid = typename AnsatzVars::Grid;
  static constexpr int dim = Grid::dimension;

/// \class DomainCache
///

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

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

    template <class Evaluators>
    void evaluateAt(LocalPosition<Grid> const& x, Evaluators const& evaluators)
    {
      u  = data.template value<0>(evaluators);
      du = data.template derivative<0>(evaluators)[0];

      xglob = cell.geometry().global(x);

      if (xglob[0] >0.25 && xglob[0]<0.75 && xglob[1] >0.25 && xglob[1]<0.75 ){
       f=1e5;
      }
      else f=0.0;
    }

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

    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.q*u*arg.value - 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 &argT,
        VariationalArg<Scalar,dim> const &argA) const
    {
      return F.kappa*argT.derivative[0]*argA.derivative[0] + F.q*argT.value*argA.value;
    }

  private:
    HeatFunctional const& F;
    typename AnsatzVars::VariableSet const& data;
    Cell<Grid> cell;
    GlobalPosition<Grid> xglob;
    Scalar f;
    Scalar u;
    Dune::FieldVector<Scalar,dim> du;
  };

/// \class BoundaryCache
///

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

    BoundaryCache(HeatFunctional const&,
                  typename AnsatzVars::VariableSet const& vars_,
                  int flags=7):
      data(vars_), e(0)
    {}

    void moveTo(FaceIterator const& entity)
    {
      e = &entity;
      penalty = 1.0e9;
    }

    template <class Evaluators>
    void evaluateAt(Dune::FieldVector<typename Grid::ctype,dim-1> const& x, Evaluators const& evaluators)
    {
      xglob = (*e)->geometry().global(x);

      u = data.template value<0>(evaluators);
      u0 = 0;
    }

    Scalar
    d0() const
    {
      return penalty*(u-u0)*(u-u0)/2;
    }

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {

        return penalty*(u-u0)*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 penalty*arg1.value*arg2.value;

    }

  private:
    typename AnsatzVars::VariableSet const& data;
    FaceIterator const* e;
    GlobalPosition<Grid> xglob;
    Scalar penalty, u, u0;
  };


/// \struct HeatFunctional constructor
///

  HeatFunctional(Scalar kappa_, Scalar q_): kappa(kappa_), q(q_)
  {
  }



/// \struct D2
///

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

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

/// \fn integrationOrder
///

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

private:
  Scalar kappa, q;
};

/// \example ht.cpp
/// show the usage of HeatFunctional describing a stationary heat transfer problem,
/// no adaptive grid refinement.
///
#endif

inverse.hh

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

#ifndef IHEATTRANSFER_HH
#define IHEATTRANSFER_HH

#include <cmath>

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


template <class RType, class VarSet>
class IHeatFunctional: public FunctionalBase<VariationalFunctional>
{
public:
  using Scalar = RType;
  using OriginVars = VarSet;
  using AnsatzVars = VarSet;
  using TestVars = VarSet;
  using Grid = typename AnsatzVars::Grid;
  using Spaces = typename AnsatzVars::Spaces;

  using MeasurementSpace = std::remove_pointer_t<typename boost::fusion::result_of::value_at_c<Spaces,1>::type>;
  using MeasurementData  = typename MeasurementSpace::template Element_t<1>;

  static constexpr int dim = Grid::dimension;

/// \class DomainCache
///

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

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

    template <class Evaluators>
    void evaluateAt(LocalPosition<Grid> const& x, Evaluators const& evaluators)
    {
      T  = data.template value<0>(evaluators);
      dT = data.template derivative<0>(evaluators)[0];

      lambda  = data.template value<1>(evaluators);
      dlambda = data.template derivative<1>(evaluators)[0];

      f  = data.template value<2>(evaluators);
      df = data.template derivative<2>(evaluators)[0];



      alpha= F.alpha;
      T_m   = F.measurementData.value(boost::fusion::at_c<1>(evaluators));

    }


    Scalar d0() const
    {
      return (T-T_m)*(T-T_m)/2 + (alpha/2 *df*df) + dT*F.kappa*dlambda + T*F.q*lambda - f*lambda ;
    }

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
    if(row ==0) return (T-T_m)*arg.value + F.kappa*arg.derivative[0] *dlambda + arg.value*F.q*lambda ;
    if(row ==1) return F.kappa*dT*arg.derivative[0] + F.q*T*arg.value - f*arg.value ;
    if(row ==2) return alpha* df * arg.derivative[0] -arg.value*lambda ;

    }

    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 &argT,
        VariationalArg<Scalar,dim> const &argA) const
    {
     if(row==0 && col ==0) return argA.value *argT.value;
     if(row==0 && col ==1) return F.kappa*argA.derivative[0]*argT.derivative[0] + F.q*argA.value*argT.value;
     if(row==0 && col ==2) return 0;

     if(row==1 && col ==0) return F.kappa*argA.derivative[0]*argT.derivative[0] + F.q *argA.value*argT.value;
     if(row==1 && col ==1) return 0;
     if(row==1 && col ==2) return -argA.value*argT.value;

     if(row==2 && col ==0) return 0;
     if(row==2 && col ==1) return -argA.value*argT.value;
     if(row==2 && col ==2) return alpha* argA.derivative[0]*argT.derivative[0]  ;
    }


  private:
    IHeatFunctional const& F;
    typename AnsatzVars::VariableSet const& data;
    Cell<Grid> cell;
    Scalar f;
    Scalar T;
    Scalar lambda;
    Scalar T_m;
    Scalar alpha;
    Dune::FieldVector<Scalar,dim> dT;
    Dune::FieldVector<Scalar,dim> dlambda;
    Dune::FieldVector<Scalar,dim> df;
  };

/// \class BoundaryCache
///

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

    BoundaryCache(IHeatFunctional const&,
                  typename AnsatzVars::VariableSet const& vars_,
                  int flags=7):
      data(vars_), e(0)
    {}

    void moveTo(FaceIterator const& entity)
    {
      e = &entity;
      penalty = 1.0e14;
    }

    template <class Evaluators>
    void evaluateAt(Dune::FieldVector<typename Grid::ctype,dim-1> const& x, Evaluators const& evaluators)
    {

      T = data.template value<0>(evaluators);
      lambda = data.template value<1>(evaluators);
      f = data.template value<2>(evaluators);
      T0 = 0;
    }

    Scalar
    d0() const
    {
      return penalty*(T-T0)*(T-T0)/2 ;
    }

    template<int row, int dim>
    Dune::FieldVector<Scalar, TestVars::template Components<row>::m>
    d1 (VariationalArg<Scalar,dim> const& arg) const
    {
      if(row==1) return penalty*(T-T0)*arg.value;
      else return 0.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
    {
      if (row==1 && col==0  ) return penalty*arg1.value*arg2.value;
      else return 0.0;
    }

  private:
    typename AnsatzVars::VariableSet const& data;
    FaceIterator const* e;
    Scalar penalty, T, T0, lambda,f;
  };


/// \struct IHeatFunctional constructor
///

 IHeatFunctional(Scalar kappa_, Scalar q_,Scalar alpha_, MeasurementData const& measurementData_): kappa(kappa_), q(q_),alpha(alpha_),measurementData(measurementData_)
  {
  }



/// \struct D2
///

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

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

/// \fn integrationOrder
///

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

private:
  Scalar kappa, q,alpha;
  MeasurementData const& measurementData;
};

#endif

Results

The resulting inverted source term

Inverse_Source.png

The resulting temperature field

Inverse_Temp.png

The value of the Lagrange multiplier

Lambda_inverse.png


Page last modified: 2026-11-10