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;
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:163
Grids in Dune are hierarchical, 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;
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:24
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))
;
for ([[maybe_unused]]
const auto& e :
vertices(gv))
;
for ([[maybe_unused]]
const auto& e :
edges(gv))
;
for ([[maybe_unused]]
const auto& e :
facets(gv))
;
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 (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