Dune Core Modules (2.8.0)

Iterating over a grid

A fundamental task in many finite element-type discretizations is iterating over the elements of a grid, for example in order to numerically compute integrals on it. All DUNE grids provide a unified interface for this and related operations.

First, we set up a simple structured grid. Here we use the Dune::YaspGrid class in four dimensions in order to demonstrate that even dimension larger than three can be used.

const int dim = 4;
using Grid = Dune::YaspGrid<dim>;
Dune::FieldVector<double,dim> len; for (auto& l : len) l=1.0;
std::array<int,dim> cells; for (auto& c : cells) c=4;
Grid grid(len,cells);
vector space out of a tensor product of fields.
Definition: fvector.hh:95
[ provides Dune::Grid ]
Definition: yaspgrid.hh:160

Grids in Dune are hierachical, i.e. they are organized into levels (originating from refinement) and entities that are not further refined. Each of these subsets is accessible via Dune::GridView and iteration over is possible only over grid views. So we extract the Dune::LeafGridView:

auto gv = grid.leafGridView();

Now we can iterate over all the entities of a certain codimension in a grid view using a range-based for loop:

const int codim = 2;
for (const auto& e : entities(gv,Dune::Codim<codim>{}))
if (!e.type().isCube()) std::cout << "not a cube" << std::endl;
IteratorRange<... > entities(const GV &gv, Codim< codim > cd)
Iterates over all entities of a GridView with the given codimension.
Static tag representing a codimension.
Definition: dimension.hh:22

As an example we extract the type of an element and test for it to be a cube.

Instead of specifying the codimension explicitly you can also use the following predefined names in the range-based for loop:

for ([[maybe_unused]] const auto& e : elements(gv)); // codim=0
for ([[maybe_unused]] const auto& e : vertices(gv)); // codim=dim
for ([[maybe_unused]] const auto& e : edges(gv)); // codim=dim-1
for ([[maybe_unused]] const auto& e : facets(gv)); // codim=1
IteratorRange<... > vertices(const GV &gv)
Iterates over all vertices (entities with dimension 0) of a GridView.
IteratorRange<... > elements(const GV &gv)
Iterates over all elements / cells (entities with codimension 0) of a GridView.
IteratorRange<... > facets(const GV &gv)
Iterates over all facets (entities with codimension 1) of a GridView.
IteratorRange<... > edges(const GV &gv)
Iterates over all edges (entities with dimension 1) of a GridView.

Finally, from entities of codimension 0 (aka elements) you can access all subentities of all codimensions using the following code:

const int mycodim = 2;
for (const auto& e : elements(gv))
for (unsigned int i=0; i<e.subEntities(mycodim); ++i)
[[maybe_unused]] auto v = e.template subEntity<codim>(i);

Full example code: recipe-iterate-over-grid.cc

Creative Commons License   |  Legal Statements / Impressum  |  Hosted by TU Dresden  |  generated with Hugo v0.111.3 (Dec 22, 23:30, 2024)