lagrangegridcreator.hh 16.4 KB
Newer Older
Praetorius, Simon's avatar
Praetorius, Simon committed
1
2
3
4
5
#pragma once

#include <cassert>
#include <cstdint>
#include <limits>
6
#include <optional>
Praetorius, Simon's avatar
Praetorius, Simon committed
7
8
9
10
11
#include <vector>

#include <dune/common/exceptions.hh>
#include <dune/common/hybridutilities.hh>
#include <dune/geometry/utility/typefromvertexcount.hh>
Stenger, Florian's avatar
Stenger, Florian committed
12
#include <dune/geometry/multilineargeometry.hh>
Praetorius, Simon's avatar
Praetorius, Simon committed
13
14
15
#include <dune/localfunctions/lagrange.hh>
#include <dune/grid/common/gridfactory.hh>

Stenger, Florian's avatar
Stenger, Florian committed
16
#include <dune/vtk/types.hh>
Praetorius, Simon's avatar
Praetorius, Simon committed
17
#include <dune/vtk/gridcreatorinterface.hh>
18
#include <dune/vtk/gridfunctions/lagrangegridfunction.hh>
Praetorius, Simon's avatar
Praetorius, Simon committed
19
20
21
22
#include <dune/vtk/utility/lagrangepoints.hh>

namespace Dune
{
Stenger, Florian's avatar
Stenger, Florian committed
23
  namespace Vtk
Praetorius, Simon's avatar
Praetorius, Simon committed
24
  {
Stenger, Florian's avatar
Stenger, Florian committed
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    // \brief Create a grid from data that represents higher (lagrange) cells.
    /**
    * The grid is created from the first nodes of a cell parametrization, representing
    * the  corner vertices. Thus a piecewise "flat" grid is constructed. The
    * parametrization is 1. passed as a local element parametrization to the
    * `insertElement()` function of a gridFactory to allow the grid itself to handle the
    * parametrization and 2. is stored internally that can be accessed by using this
    * GridCreator object as a grid function, or by extracting locally the parametrization
    * on each existing grid element after creation of the grid.
    *
    * So, the LagrangeGridCreator models both, a `GridCreator` and a `GridFunction`.
    **/
    template <class GridType>
    struct LagrangeGridCreator
        : public GridCreatorInterface<GridType, LagrangeGridCreator<GridType>>
Praetorius, Simon's avatar
Praetorius, Simon committed
40
    {
Stenger, Florian's avatar
Stenger, Florian committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
      using Self = LagrangeGridCreator;
      using Super = GridCreatorInterface<GridType, Self>;
      using GlobalCoordinate = typename Super::GlobalCoordinate;

      using Nodes = std::vector<GlobalCoordinate>;

      struct ElementParametrization
      {
        GeometryType type;                  //< Geometry type of the element
        std::vector<std::int64_t> nodes;    //< Indices of the w.r.t. `nodes_` vector
        std::vector<unsigned int> corners;  //< Insertion-indices of the element corner nodes
      };

      using Parametrization = std::vector<ElementParametrization>;
      using Element = typename GridType::template Codim<0>::Entity;
      using LocalCoordinate = typename Element::Geometry::LocalCoordinate;

      class LocalParametrization;
      class LocalFunction;

    public:
62
      using LocalGeometry = MultiLinearGeometry<typename Element::Geometry::ctype,Element::dimension,Element::dimension>;
Stenger, Florian's avatar
Stenger, Florian committed
63

64
65
66
    public:
      using Super::Super;
      using Super::factory;
Stenger, Florian's avatar
Stenger, Florian committed
67
68
69
70
71
72
73
74

      /// Implementation of the interface function `insertVertices()`
      void insertVerticesImpl (std::vector<GlobalCoordinate> const& points,
                              std::vector<std::uint64_t> const& /*point_ids*/)
      {
        // store point coordinates in member variable
        nodes_ = points;
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
75

Stenger, Florian's avatar
Stenger, Florian committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
      template <class F>
      using HasParametrizedElements = decltype(std::declval<F>().insertElement(std::declval<GeometryType>(),
        std::declval<std::vector<unsigned int> const&>(), std::declval<std::function<GlobalCoordinate(LocalCoordinate)>>()));

      /// Implementation of the interface function `insertElements()`
      void insertElementsImpl (std::vector<std::uint8_t> const& types,
                              std::vector<std::int64_t> const& offsets,
                              std::vector<std::int64_t> const& connectivity)
      {
        assert(nodes_.size() > 0);

        // mapping of node index to element-vertex index
        std::vector<std::int64_t> elementVertices(nodes_.size(), -1);
        parametrization_.reserve(types.size());

        std::int64_t vertexIndex = 0;
        for (std::size_t i = 0; i < types.size(); ++i) {
          auto type = Vtk::to_geometry(types[i]);
          if (type.dim() != GridType::dimension)
            continue;

          Vtk::CellType cellType{type};
          auto refElem = referenceElement<double,GridType::dimension>(type);

          std::int64_t shift = (i == 0 ? 0 : offsets[i-1]);
          int nNodes = offsets[i] - shift;
          int nVertices = refElem.size(GridType::dimension);

          // insert vertices into grid and construct element vertices
          std::vector<unsigned int> element(nVertices);
          for (int j = 0; j < nVertices; ++j) {
            auto index = connectivity.at(shift + j);
            auto& vertex = elementVertices.at(index);
            if (vertex < 0) {
              factory().insertVertex(nodes_.at(index));
              vertex = vertexIndex++;
            }
            element[j] = vertex;
Praetorius, Simon's avatar
Praetorius, Simon committed
114
115
          }

Stenger, Florian's avatar
Stenger, Florian committed
116
117
118
119
          // permute element indices
          if (!cellType.noPermutation()) {
            // apply index permutation
            std::vector<unsigned int> cell(element.size());
120
            for (std::size_t j = 0; j < element.size(); ++j)
Stenger, Florian's avatar
Stenger, Florian committed
121
122
123
              cell[j] = element[cellType.permutation(j)];
            std::swap(element, cell);
          }
Praetorius, Simon's avatar
Praetorius, Simon committed
124

Stenger, Florian's avatar
Stenger, Florian committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
          // fill vector of element parametrizations
          parametrization_.push_back(ElementParametrization{type});
          auto& param = parametrization_.back();

          param.nodes.resize(nNodes);
          for (int j = 0; j < nNodes; ++j)
            param.nodes[j] = connectivity.at(shift + j);
          param.corners = element;

          // try to create element with parametrization
          if constexpr (Std::is_detected_v<HasParametrizedElements, GridFactory<GridType>>) {
            try {
              factory().insertElement(type, element,
                localParametrization(parametrization_.size()-1));
            } catch (Dune::GridError const& /* notImplemented */) {
              factory().insertElement(type, element);
            }
          } else {
Praetorius, Simon's avatar
Praetorius, Simon committed
143
144
145
146
147
            factory().insertElement(type, element);
          }
        }
      }

Stenger, Florian's avatar
Stenger, Florian committed
148
149
150
151
152
153
154
155
156
157
158
159
      /// \brief Construct an element parametrization
      /**
      * The returned LocalParametrization is a mapping `GlobalCoordinate(LocalCoordinate)`
      * where `LocalCoordinate is w.r.t. the local coordinate system in an element with
      * given `insertionIndex` (defined by the inserted corner vertices) and
      * `GlobalCoordinate` a world coordinate in the parametrized grid.
      **/
      LocalParametrization localParametrization (unsigned int insertionIndex) const
      {
        assert(!nodes_.empty() && !parametrization_.empty());
        auto const& localParam = parametrization_.at(insertionIndex);
        return LocalParametrization{nodes_, localParam, order(localParam)};
Praetorius, Simon's avatar
Praetorius, Simon committed
160
161
      }

Stenger, Florian's avatar
Stenger, Florian committed
162
163
164
165
166
167
168
169
      /// \brief Construct an element parametrization
      /**
      * The returned LocalParametrization is a mapping `GlobalCoordinate(LocalCoordinate)`
      * where `LocalCoordinate is w.r.t. the local coordinate system in the passed element
      * and `GlobalCoordinate` a world coordinate in the parametrized grid.
      **/
      LocalParametrization localParametrization (Element const& element) const
      {
170
        VTK_ASSERT(!nodes_.empty() && !parametrization_.empty());
Stenger, Florian's avatar
Stenger, Florian committed
171
172
173

        unsigned int insertionIndex = factory().insertionIndex(element);
        auto const& localParam = parametrization_.at(insertionIndex);
174
        VTK_ASSERT(element.type() == localParam.type);
Stenger, Florian's avatar
Stenger, Florian committed
175

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
        return {nodes_, localParam, order(localParam), localGeometry(element, localParam)};
      }

      /// \brief Construct a transformation of local element coordinates
      /**
      * An element might have a different local coordinate system than the coordinate
      * system used to defined the element parametrization. Thus coordinate transform
      * of the local parametrization is needed for element-local evaluations. This
      * local geometry transform is obtained by figuring out the permutation of corners
      * in the element corresponding to the inserted corner vertices.
      **/
      LocalGeometry localGeometry (Element const& element) const
      {
        VTK_ASSERT(!nodes_.empty() && !parametrization_.empty());

        unsigned int insertionIndex = factory().insertionIndex(element);
        auto const& localParam = parametrization_.at(insertionIndex);
        VTK_ASSERT(element.type() == localParam.type);

        return localGeometry(element, localParam);
      }

    private:
      // implementation details of localGeometry()
      LocalGeometry localGeometry (Element const& element, ElementParametrization const& localParam) const
      {
Stenger, Florian's avatar
Stenger, Florian committed
202
203
204
205
206
207
208
209
210
        // collect indices of vertices
        std::vector<unsigned int> indices(element.subEntities(GridType::dimension));
        for (unsigned int i = 0; i < element.subEntities(GridType::dimension); ++i)
          indices[i] = factory().insertionIndex(element.template subEntity<GridType::dimension>(i));

        // calculate permutation vector
        std::vector<unsigned int> permutation(indices.size());
        for (std::size_t i = 0; i < indices.size(); ++i) {
          auto it = std::find(localParam.corners.begin(), localParam.corners.end(), indices[i]);
211
          VTK_ASSERT(it != localParam.corners.end());
Stenger, Florian's avatar
Stenger, Florian committed
212
213
          permutation[i] = std::distance(localParam.corners.begin(), it);
        }
Praetorius, Simon's avatar
Praetorius, Simon committed
214

215
216
217
218
219
220
        auto refElem = referenceElement<typename Element::Geometry::ctype,Element::dimension>(localParam.type);
        std::vector<LocalCoordinate> corners(permutation.size());
        for (std::size_t i = 0; i < permutation.size(); ++i)
          corners[i] = refElem.position(permutation[i], Element::dimension);

        return {localParam.type, corners};
Stenger, Florian's avatar
Stenger, Florian committed
221
      }
222

223
224
    public:

Stenger, Florian's avatar
Stenger, Florian committed
225
      /// Determine lagrange order from number of points
226
      int order (GeometryType type, std::size_t nNodes) const
Stenger, Florian's avatar
Stenger, Florian committed
227
      {
228
        for (int o = 1; o <= int(nNodes); ++o)
229
          if (numLagrangePoints(type.id(), type.dim(), o) == std::size_t(nNodes))
Stenger, Florian's avatar
Stenger, Florian committed
230
231
232
233
            return o;

        return 1;
      }
234

235
236
237
238
239
      int order (ElementParametrization const& localParam) const
      {
        return order(localParam.type, localParam.nodes.size());
      }

Stenger, Florian's avatar
Stenger, Florian committed
240
      /// Determine lagrange order from number of points from the first element parametrization
241
      int order () const
Stenger, Florian's avatar
Stenger, Florian committed
242
243
      {
        assert(!parametrization_.empty());
244
245
        auto const& localParam = parametrization_.front();
        return order(localParam);
Stenger, Florian's avatar
Stenger, Florian committed
246
      }
247

Stenger, Florian's avatar
Stenger, Florian committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    public:
      /// \brief Local function representing the parametrization of the grid.
      /**
      * The returned object models Functions::Concept::LocalFunction
      * and can thus be bound to an element of the created grid and evaluated in
      * the local coordinates of the bound element.
      *
      * It is implemented in terms of the \ref LocalParametrization function
      * returned by the method \ref localParametrization(element). See comments
      * there for further details.
      *
      * Note, this methods requires the GridCreator to be based by
      * lvalue-reference. This is necessary, since we want to guarantee that all
      * internal storage is preserved while evaluating the local function.
      **/
      friend LocalFunction localFunction (LagrangeGridCreator& gridCreator)
      {
        return LocalFunction{gridCreator};
      }
267

Stenger, Florian's avatar
Stenger, Florian committed
268
269
270
271
      friend LocalFunction localFunction (LagrangeGridCreator const& gridCreator)
      {
        return LocalFunction{gridCreator};
      }
272

Stenger, Florian's avatar
Stenger, Florian committed
273
274
275
276
277
      friend LocalFunction localFunction (LagrangeGridCreator&& gridCreator)
      {
        DUNE_THROW(Dune::Exception, "Cannot pass temporary LagrangeGridCreator to localFunction(). Pass an lvalue-reference instead.");
        return LocalFunction{gridCreator};
      }
278

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
      std::string name () const
      {
        return "LagrangeParametrization";
      }

      int numComponents () const
      {
        return GlobalCoordinate::size();
      }

      Vtk::DataTypes dataType () const
      {
        return dataTypeOf<typename Element::Geometry::ctype>();
      }

Stenger, Florian's avatar
Stenger, Florian committed
294
295
296
297
298
299
300
301
302
303
304
305
      struct EntitySet
      {
        using Grid = GridType;
        using GlobalCoordinate = typename Self::GlobalCoordinate;
      };

      /// Dummy function returning a placeholder entityset
      EntitySet entitySet () const
      {
        assert(false && "Should not be used!");
        return EntitySet{};
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
306

Stenger, Florian's avatar
Stenger, Florian committed
307
308
309
310
311
312
      /// Dummy function returning a placeholder entityset
      GlobalCoordinate operator() (GlobalCoordinate const&) const
      {
        assert(false && "Should not be used!");
        return GlobalCoordinate{};
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
313

Stenger, Florian's avatar
Stenger, Florian committed
314
315
316
    private:
      /// All point coordinates inclusing the higher-order lagrange points
      Nodes nodes_;
Praetorius, Simon's avatar
Praetorius, Simon committed
317

Stenger, Florian's avatar
Stenger, Florian committed
318
319
320
      /// Parametrization for all elements
      Parametrization parametrization_;
    };
Praetorius, Simon's avatar
Praetorius, Simon committed
321

322
323
324
325
326
327
328
329
330
331
    // deduction guides
    template <class Grid>
    LagrangeGridCreator(GridFactory<Grid>&)
      -> LagrangeGridCreator<Grid>;

    template <class GridType, class FieldType, class Context>
    struct AssociatedGridFunction<LagrangeGridCreator<GridType>, FieldType, Context>
    {
      using type = LagrangeGridFunction<GridType, FieldType, Context>;
    };
Praetorius, Simon's avatar
Praetorius, Simon committed
332

Stenger, Florian's avatar
Stenger, Florian committed
333
334
    template <class Grid>
    class LagrangeGridCreator<Grid>::LocalParametrization
Praetorius, Simon's avatar
Praetorius, Simon committed
335
    {
Stenger, Florian's avatar
Stenger, Florian committed
336
337
338
339
340
341
342
343
344
345
346
347
348
      using ctype = typename Grid::ctype;

      using GlobalCoordinate = typename Grid::template Codim<0>::Entity::Geometry::GlobalCoordinate;
      using LocalCoordinate = typename Grid::template Codim<0>::Entity::Geometry::LocalCoordinate;
      using LocalGeometry = MultiLinearGeometry<ctype,Grid::dimension,Grid::dimension>;

      using LocalFE = LagrangeLocalFiniteElement<Vtk::LagrangePointSet, Grid::dimension, ctype, ctype>;
      using LocalBasis = typename LocalFE::Traits::LocalBasisType;
      using LocalBasisTraits = typename LocalBasis::Traits;

    public:
      /// Construct a local element parametrization
      template <class Nodes, class LocalParam>
349
      LocalParametrization (Nodes const& nodes, LocalParam const& param, int order)
Stenger, Florian's avatar
Stenger, Florian committed
350
351
352
353
354
355
        : localFE_(param.type, order)
        , localNodes_(param.nodes.size())
      {
        for (std::size_t i = 0; i < localNodes_.size(); ++i)
          localNodes_[i] = nodes[param.nodes[i]];
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
356

Stenger, Florian's avatar
Stenger, Florian committed
357
      /// Construct a local element parametrization for elements with permuted corners
358
359
      template <class Nodes, class LocalParam, class LG>
      LocalParametrization (Nodes const& nodes, LocalParam const& param, int order, LG&& localGeometry)
Stenger, Florian's avatar
Stenger, Florian committed
360
361
        : LocalParametrization(nodes, param, order)
      {
362
        localGeometry_.emplace(std::forward<LG>(localGeometry));
Stenger, Florian's avatar
Stenger, Florian committed
363
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
364

Stenger, Florian's avatar
Stenger, Florian committed
365
366
367
368
369
370
      /// Evaluate the local parametrization in local coordinates
      template <class LocalCoordinate>
      GlobalCoordinate operator() (LocalCoordinate const& local) const
      {
        // map coordinates if element corners are permuted
        LocalCoordinate x = localGeometry_ ? localGeometry_->global(local) : local;
Praetorius, Simon's avatar
Praetorius, Simon committed
371

Stenger, Florian's avatar
Stenger, Florian committed
372
373
374
        LocalBasis const& localBasis = localFE_.localBasis();
        localBasis.evaluateFunction(x, shapeValues_);
        assert(shapeValues_.size() == localNodes_.size());
Praetorius, Simon's avatar
Praetorius, Simon committed
375

376
377
        using field_type = typename LocalBasisTraits::RangeType::field_type;

Stenger, Florian's avatar
Stenger, Florian committed
378
379
        GlobalCoordinate out(0);
        for (std::size_t i = 0; i < shapeValues_.size(); ++i)
380
          out.axpy(field_type(shapeValues_[i]), localNodes_[i]);
Praetorius, Simon's avatar
Praetorius, Simon committed
381

Stenger, Florian's avatar
Stenger, Florian committed
382
383
        return out;
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
384

Stenger, Florian's avatar
Stenger, Florian committed
385
386
387
388
    private:
      LocalFE localFE_;
      std::vector<GlobalCoordinate> localNodes_;
      std::optional<LocalGeometry> localGeometry_;
Praetorius, Simon's avatar
Praetorius, Simon committed
389

Stenger, Florian's avatar
Stenger, Florian committed
390
391
      mutable std::vector<typename LocalBasisTraits::RangeType> shapeValues_;
    };
Praetorius, Simon's avatar
Praetorius, Simon committed
392

393

Stenger, Florian's avatar
Stenger, Florian committed
394
395
    template <class Grid>
    class LagrangeGridCreator<Grid>::LocalFunction
Praetorius, Simon's avatar
Praetorius, Simon committed
396
    {
Stenger, Florian's avatar
Stenger, Florian committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
      using ctype = typename Grid::ctype;
      using LocalContext = typename Grid::template Codim<0>::Entity;
      using GlobalCoordinate = typename LocalContext::Geometry::GlobalCoordinate;
      using LocalCoordinate = typename LocalContext::Geometry::LocalCoordinate;
      using LocalParametrization = typename LagrangeGridCreator::LocalParametrization;

    public:
      explicit LocalFunction (LagrangeGridCreator const& gridCreator)
        : gridCreator_(&gridCreator)
      {}

      explicit LocalFunction (LagrangeGridCreator&& gridCreator) = delete;

      /// Collect a local parametrization on the element
      void bind (LocalContext const& element)
      {
        localContext_ = element;
        localParametrization_.emplace(gridCreator_->localParametrization(element));
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
416

Stenger, Florian's avatar
Stenger, Florian committed
417
      void unbind () { /* do nothing */ }
Praetorius, Simon's avatar
Praetorius, Simon committed
418

Stenger, Florian's avatar
Stenger, Florian committed
419
420
421
422
423
424
      /// Evaluate the local parametrization in local coordinates
      GlobalCoordinate operator() (LocalCoordinate const& local) const
      {
        assert(!!localParametrization_);
        return (*localParametrization_)(local);
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
425

Stenger, Florian's avatar
Stenger, Florian committed
426
427
428
429
430
      /// Return the bound element
      LocalContext const& localContext () const
      {
        return localContext_;
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
431

Stenger, Florian's avatar
Stenger, Florian committed
432
433
    private:
      LagrangeGridCreator const* gridCreator_;
Praetorius, Simon's avatar
Praetorius, Simon committed
434

Stenger, Florian's avatar
Stenger, Florian committed
435
436
437
      LocalContext localContext_;
      std::optional<LocalParametrization> localParametrization_;
    };
Praetorius, Simon's avatar
Praetorius, Simon committed
438

Stenger, Florian's avatar
Stenger, Florian committed
439
  } // end namespace Vtk
Praetorius, Simon's avatar
Praetorius, Simon committed
440
} // end namespace Dune