mmiterator.hh 10.5 KB
Newer Older
Praetorius, Simon's avatar
Praetorius, Simon committed
1 2 3 4 5 6 7
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:
#ifndef DUNE_MULTIMESH_ITERATOR_HH
#define DUNE_MULTIMESH_ITERATOR_HH

#include <numeric>
#include <stack>
8
#include <variant>
Praetorius, Simon's avatar
Praetorius, Simon committed
9 10

#include <dune/common/iteratorfacades.hh>
11
#include <dune/common/std/type_traits.hh>
Praetorius, Simon's avatar
Praetorius, Simon committed
12 13 14
#include <dune/grid/common/exceptions.hh>
#include <dune/grid/common/gridenums.hh>

Praetorius, Simon's avatar
Praetorius, Simon committed
15
#include "mmentity.hh"
16
#include "mmhierarchiciterator.hh"
Praetorius, Simon's avatar
Praetorius, Simon committed
17 18 19 20 21 22

namespace Dune
{
  /** \brief Iterator over all entities of a given codimension and level of a grid.
   *  \ingroup MultiMesh
   */
23
  template <int codim, PartitionIteratorType pitype, class HostGrid>
Praetorius, Simon's avatar
Praetorius, Simon committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
  class MultiMeshIterator
  {
  public:
    template <class... Args>
    MultiMeshIterator(Args&&... args)
    {
      DUNE_THROW(NotImplemented, "Not implemented for entity of codim != 0!");
    }

    int operator*() const { return 0; }
    MultiMeshIterator& operator++() { return *this; }
    MultiMeshIterator operator++(int) { return *this; }
    bool operator!=(MultiMeshIterator const&) const { return false; }
  };


  // Implemented for codim 0 entities only
41 42 43 44 45
  template <PartitionIteratorType pitype, class HostGrid>
  class MultiMeshIterator<0, pitype, HostGrid>
      : public ForwardIteratorFacade<MultiMeshIterator<0,pitype,HostGrid>,
            MultiEntity<HostGrid>,
            MultiEntity<HostGrid> const&>
Praetorius, Simon's avatar
Praetorius, Simon committed
46 47 48 49
  {
  private:
    // LevelIterator to the equivalent entity in the host grid
    using HostGridLevelIterator =
50
      typename HostGrid::template Codim<0>::template Partition<pitype>::LevelIterator;
Praetorius, Simon's avatar
Praetorius, Simon committed
51

52
    using HostEntity = typename HostGrid::template Codim<0>::Entity;
Praetorius, Simon's avatar
Praetorius, Simon committed
53

54 55
    using EntityTest  = typename MultiMeshHierarchicIterator<HostGrid>::EntityTest;
    using EntityStack = typename MultiMeshHierarchicIterator<HostGrid>::EntityStack;
Praetorius, Simon's avatar
Praetorius, Simon committed
56 57 58

  public:
    /// Constructor. Stores a pointer to the grid
59
    template <class GridImp>
60 61 62 63
    MultiMeshIterator (const GridImp* multiMesh, int level)
      : incrementAllowed_(multiMesh->size(), true)
      , contains_(multiMesh->size(), EntityTest{[level](const HostEntity& entity) { return entity.level() == level; }})
      , maxLevel_(multiMesh->size(), level)
64
      , multiEntity_(multiMesh->size())
Praetorius, Simon's avatar
Praetorius, Simon committed
65
    {
66
      for (auto const& grid : multiMesh->grids_) {
Praetorius, Simon's avatar
Praetorius, Simon committed
67 68 69 70 71
        macroIterators_.push_back(grid->levelGridView(0).template begin<0,pitype>());
        macroEndIterators_.push_back(grid->levelGridView(0).template end<0,pitype>());
      }

      // go to first leaf entity on all grids
72 73 74 75
      entityStacks_.reserve(multiMesh->size());
      for (std::size_t i = 0; i < multiMesh->size(); ++i) {
        maxLevel_[i] = (*multiMesh)[i].maxLevel();
        entityStacks_.emplace_back((*multiMesh)[i].maxLevel());
Praetorius, Simon's avatar
Praetorius, Simon committed
76
        initialIncrement(i);
77
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
78 79 80 81 82 83 84
    }

    /// Constructor which create the end iterator
    /**
     * \param  multiMesh  Pointer to grid instance
     * \param  endDummy   Here only to distinguish it from the other constructor
     */
85
    template <class GridImp>
Praetorius, Simon's avatar
Praetorius, Simon committed
86 87
    MultiMeshIterator (const GridImp* multiMesh, int level, bool endDummy)
    {
88
      for (auto const& grid : multiMesh->grids_)
Praetorius, Simon's avatar
Praetorius, Simon committed
89 90 91
        macroIterators_.push_back(grid->levelGridView(0).template end<0,pitype>());
    }

Praetorius, Simon's avatar
Praetorius, Simon committed
92
    /// Constructor which create the leaf-iterator
93
    template <class GridImp>
Praetorius, Simon's avatar
Praetorius, Simon committed
94 95 96 97
    MultiMeshIterator (const GridImp* multiMesh)
      : MultiMeshIterator{multiMesh, -1}
    {}

Praetorius, Simon's avatar
Praetorius, Simon committed
98
    /// Constructor which create the end leaf-iterator
99
    template <class GridImp>
Praetorius, Simon's avatar
Praetorius, Simon committed
100 101 102 103
    MultiMeshIterator (const GridImp* multiMesh, bool endDummy)
      : MultiMeshIterator{multiMesh, -1, endDummy}
    {}

104
    /// Construct an iterator from n gridViews of possibly different type
105 106
    template <class... GridViews,
      std::enable_if_t<not Std::disjunction<std::is_same<GridViews,bool>...>::value, int> = 0>
107
    MultiMeshIterator (GridViews const&... gridViews)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      : incrementAllowed_(sizeof...(GridViews), true)
      , maxLevel_{gridViews.grid().maxLevel()...}
      , multiEntity_(sizeof...(GridViews))
      , macroIterators_{gridViews.grid().levelGridView(0).template begin<0,pitype>()...}
      , macroEndIterators_{gridViews.grid().levelGridView(0).template end<0,pitype>()...}
      , entityStacks_{EntityStack{gridViews.grid().maxLevel()}...}
    {
      contains_.reserve(sizeof...(GridViews));
      Hybrid::forEach(std::forward_as_tuple(gridViews...), [this](auto const& gv) {
        contains_.emplace_back([gv](const HostEntity& entity) { return gv.contains(entity); });
      });

      for (std::size_t i = 0; i < sizeof...(GridViews); ++i)
        initialIncrement(i);
    }

    template <class... GridViews>
125
    MultiMeshIterator (bool endDummy, GridViews const&... gridViews)
126 127 128
      : macroIterators_{gridViews.grid().levelGridView(0).template end<0,pitype>()...}
    {}

129
#if DUNE_HAVE_CXX_VARIANT
130 131
    /// Construct an iterator from a vector of GridViews, where each GridView can be
    /// either a leaf- or a level-gridView, thus we need to use a variant.
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    template <class... GV>
    MultiMeshIterator (const std::vector<std::variant<GV...>>& gridViews)
      : incrementAllowed_(gridViews.size(), true)
      , multiEntity_(gridViews.size())
    {
      contains_.reserve(gridViews.size());
      entityStacks_.reserve(gridViews.size());
      maxLevel_.reserve(gridViews.size());

      for (auto const& gvs : gridViews) {
        macroIterators_.push_back(std::visit([](auto const& gv) {
          return gv.grid().levelGridView(0).template begin<0,pitype>(); }, gvs));
        macroEndIterators_.push_back(std::visit([](auto const& gv) {
          return gv.grid().levelGridView(0).template end<0,pitype>(); }, gvs));
        contains_.emplace_back(std::visit([](auto const& gv) {
          return EntityTest{[gv](const HostEntity& entity) { return gv.contains(entity); }}; }, gvs));
        maxLevel_.push_back(std::visit([](auto const& gv) { return gv.grid().maxLevel(); }, gvs));
        entityStacks_.emplace_back(std::visit([](auto const& gv) { return gv.grid().maxLevel(); }, gvs));
      }

      // go to first leaf entity on all grids
      for (std::size_t i = 0; i < entityStacks_.size(); ++i)
        initialIncrement(i);
    }

    template <class... GV>
    MultiMeshIterator (const std::vector<std::variant<GV...>>& gridViews, bool endDummy)
    {
      for (auto const& gvs : gridViews) {
        macroIterators_.push_back(std::visit([](auto const& gv) {
          return gv.grid().levelGridView(0).template end<0,pitype>(); }, gvs));
      }
    }
#endif
Praetorius, Simon's avatar
Praetorius, Simon committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179

    /// prefix increment
    void increment ()
    {
      for (std::size_t i = 0; i < entityStacks_.size(); ++i)
        incrementAllowed_[i] = incrementAllowed(i);

      for (std::size_t i = 0; i < entityStacks_.size(); ++i) {
        if (incrementAllowed_[i])
          increment(i);
      }
    }

    /// dereferencing
180
    MultiEntity<HostGrid> const& dereference () const
Praetorius, Simon's avatar
Praetorius, Simon committed
181
    {
182 183 184 185 186 187
      // update entries in multiEntity that have changed
      for (std::size_t i = 0; i < entityStacks_.size(); ++i) {
        if (incrementAllowed_[i])
          multiEntity_[i] = dereference(i);
      }
      return multiEntity_;
Praetorius, Simon's avatar
Praetorius, Simon committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    }

    /// equality
    bool equals (const MultiMeshIterator& that) const
    {
      return macroIterators_ == that.macroIterators_;
    }

  protected:
    // got to next entity in grid i
    void increment (std::size_t i)
    {
      auto& entityStack = entityStacks_[i];
      auto& macroIt = macroIterators_[i];
      auto const& macroEnd = macroEndIterators_[i];

      // 1. go up in tree or to next entity on current level until we can go down again
      while (!entityStack.empty()) {
        auto& top = entityStack.top();
        ++top.it;
        if (top.it == top.end) {
          entityStack.pop();
        } else {
          break;
        }
      }

      // 2. if entityStack is empty, go to next macroElement
      if (entityStack.empty()) {
        ++macroIt;
        if (macroIt == macroEnd)
          return;
      }

      // 3. go down in tree until leaf entity
223 224 225
      auto child = dereference(i);
      for (; !(contains_[i](child) || child.isLeaf()); child = dereference(i)) {
        assert(child.isRegular() && "No irregular elements allowed in multi-mesh traversal");
226
        entityStack.emplace(child);
227
        assert(entityStack.size() <= maxLevel_[i]);
228
      }
229

230
      // assert(contains_[i](child) && "No valid child element found in gridView");
Praetorius, Simon's avatar
Praetorius, Simon committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    }

    /// Return true, if all stacks with size > stack[i].size are finished
    bool incrementAllowed (std::size_t i) const
    {
      std::size_t size = entityStacks_[i].size();
      return std::accumulate(entityStacks_.begin(), entityStacks_.end(), true,
        [i,size](bool allowed, auto const& entityStack) {
          return allowed && (entityStack.size() <= size || entityStack.finished(size));
        });
    }

    // got to first leaf entity on grid i
    void initialIncrement (std::size_t i)
    {
      auto& entityStack = entityStacks_[i];
      auto& macroIt = macroIterators_[i];
      auto const& macroEnd = macroEndIterators_[i];

250
      assert(entityStack.empty());
Praetorius, Simon's avatar
Praetorius, Simon committed
251 252 253
      if (macroIt == macroEnd)
        return;

254 255 256 257
      // 1. go down in tree until leaf entity
      auto child = dereference(i);
      for (; !(contains_[i](child) || child.isLeaf()); child = dereference(i)) {
        assert(child.isRegular() && "No irregular elements allowed in multi-mesh traversal");
258
        entityStack.emplace(child);
259
        assert(entityStack.size() <= maxLevel_[i]);
260
      }
261

262
      // assert(contains_[i](child) && "No valid child element found in gridView");
Praetorius, Simon's avatar
Praetorius, Simon committed
263 264 265 266
    }

    HostEntity dereference (std::size_t i) const
    {
267 268
      if (entityStacks_[i].empty()) {
        assert(macroIterators_[i] != macroEndIterators_[i]);
269
        return *macroIterators_[i];
270 271
      } else {
        assert(entityStacks_[i].top().it != entityStacks_[i].top().end);
272
        return *entityStacks_[i].top().it;
273
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
274 275 276
    }

  private:
277 278 279 280
    std::vector<bool> incrementAllowed_;
    std::vector<EntityTest> contains_;
    std::vector<int> maxLevel_;

281
    mutable MultiEntity<HostGrid> multiEntity_;
Praetorius, Simon's avatar
Praetorius, Simon committed
282 283 284 285 286 287

    std::vector<HostGridLevelIterator> macroIterators_;
    std::vector<HostGridLevelIterator> macroEndIterators_;
    std::vector<EntityStack> entityStacks_;
  };

288 289 290 291
  template <class... GridViews>
  inline auto multi_elements(GridViews const&... gridViews)
  {
    using GridView0 = std::tuple_element_t<0,std::tuple<GridViews...>>;
Praetorius, Simon's avatar
Praetorius, Simon committed
292
    using Iterator = MultiMeshIterator<0,All_Partition,typename GridView0::Grid>;
293
    using Range = IteratorRange<Iterator>;
294 295
    return Range{ Iterator{gridViews...},
                  Iterator{true, gridViews...} };
296 297
  }

Praetorius, Simon's avatar
Praetorius, Simon committed
298 299 300
}  // end namespace Dune

#endif // DUNE_MULTIMESH_ITERATOR_HH