This file is indexed.

/usr/include/dune/istl/matrixredistribute.hh is in libdune-istl-dev 2.5.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
166
167
168
169
170
171
172
173
174
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
// vi: set et ts=4 sw=2 sts=2:
#ifndef DUNE_ISTL_MATRIXREDISTRIBUTE_HH
#define DUNE_ISTL_MATRIXREDISTRIBUTE_HH
#include <memory>
#include "repartition.hh"
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/indexset.hh>
#include <dune/common/unused.hh>
#include <dune/istl/owneroverlapcopy.hh>
#include <dune/istl/paamg/pinfo.hh>
/**
 * @file
 * @brief Functionality for redistributing a sparse matrix.
 * @author Markus Blatt
 */
namespace Dune
{
  template<typename  T>
  struct RedistributeInformation
  {
    bool isSetup() const
    {
      return false;
    }
    template<class D>
    void redistribute(const D& from, D& to) const
    {
      DUNE_UNUSED_PARAMETER(from);
      DUNE_UNUSED_PARAMETER(to);
    }

    template<class D>
    void redistributeBackward(D& from, const D& to) const
    {
      DUNE_UNUSED_PARAMETER(from);
      DUNE_UNUSED_PARAMETER(to);
    }

    void resetSetup()
    {}

    void setNoRows(std::size_t size)
    {
      DUNE_UNUSED_PARAMETER(size);
    }

    void setNoCopyRows(std::size_t size)
    {
      DUNE_UNUSED_PARAMETER(size);
    }

    void setNoBackwardsCopyRows(std::size_t size)
    {
      DUNE_UNUSED_PARAMETER(size);
    }

    std::size_t getRowSize(std::size_t index) const
    {
      DUNE_UNUSED_PARAMETER(index);
      return -1;
    }

    std::size_t getCopyRowSize(std::size_t index) const
    {
      DUNE_UNUSED_PARAMETER(index);
      return -1;
    }

    std::size_t getBackwardsCopyRowSize(std::size_t index) const
    {
      DUNE_UNUSED_PARAMETER(index);
      return -1;
    }

  };

#if HAVE_MPI
  template<typename  T, typename T1>
  class RedistributeInformation<OwnerOverlapCopyCommunication<T,T1> >
  {
  public:
    typedef OwnerOverlapCopyCommunication<T,T1> Comm;

    RedistributeInformation()
      : interface(), setup_(false)
    {}

    RedistributeInterface& getInterface()
    {
      return interface;
    }
    template<typename IS>
    void checkInterface(const IS& source,
                        const IS& target, MPI_Comm comm)
    {
      auto ri = std::make_unique<RemoteIndices<IS> >(source, target, comm);
      ri->template rebuild<true>();
      Interface inf;
      typename OwnerOverlapCopyCommunication<int>::OwnerSet flags;
      int rank;
      MPI_Comm_rank(MPI_COMM_WORLD, &rank);
      inf.free();
      inf.build(*ri, flags, flags);


#ifdef DEBUG_REPART
      if(inf!=interface) {

        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
        if(rank==0)
          std::cout<<"Interfaces do not match!"<<std::endl;
        std::cout<<rank<<": redist interface new :"<<inf<<std::endl;
        std::cout<<rank<<": redist interface :"<<interface<<std::endl;

        throw "autsch!";
      }
#endif
    }
    void setSetup()
    {
      setup_=true;
      interface.strip();
    }

    void resetSetup()
    {
      setup_=false;
    }

    template<class GatherScatter, class D>
    void redistribute(const D& from, D& to) const
    {
      BufferedCommunicator communicator;
      communicator.template build<D>(from,to, interface);
      communicator.template forward<GatherScatter>(from, to);
      communicator.free();
    }
    template<class GatherScatter, class D>
    void redistributeBackward(D& from, const D& to) const
    {

      BufferedCommunicator communicator;
      communicator.template build<D>(from,to, interface);
      communicator.template backward<GatherScatter>(from, to);
      communicator.free();
    }

    template<class D>
    void redistribute(const D& from, D& to) const
    {
      redistribute<CopyGatherScatter<D> >(from,to);
    }
    template<class D>
    void redistributeBackward(D& from, const D& to) const
    {
      redistributeBackward<CopyGatherScatter<D> >(from,to);
    }
    bool isSetup() const
    {
      return setup_;
    }

    void reserve(std::size_t size)
    {}

    std::size_t& getRowSize(std::size_t index)
    {
      return rowSize[index];
    }

    std::size_t getRowSize(std::size_t index) const
    {
      return rowSize[index];
    }

    std::size_t& getCopyRowSize(std::size_t index)
    {
      return copyrowSize[index];
    }

    std::size_t getCopyRowSize(std::size_t index) const
    {
      return copyrowSize[index];
    }

    std::size_t& getBackwardsCopyRowSize(std::size_t index)
    {
      return backwardscopyrowSize[index];
    }

    std::size_t getBackwardsCopyRowSize(std::size_t index) const
    {
      return backwardscopyrowSize[index];
    }

    void setNoRows(std::size_t rows)
    {
      rowSize.resize(rows, 0);
    }

    void setNoCopyRows(std::size_t rows)
    {
      copyrowSize.resize(rows, 0);
    }

    void setNoBackwardsCopyRows(std::size_t rows)
    {
      backwardscopyrowSize.resize(rows, 0);
    }

  private:
    std::vector<std::size_t> rowSize;
    std::vector<std::size_t> copyrowSize;
    std::vector<std::size_t> backwardscopyrowSize;
    RedistributeInterface interface;
    bool setup_;
  };

  /**
   * @brief Utility class to communicate and set the row sizes
   * of a redistributed matrix.
   *
   * @tparam M The type of the matrix that the row size
   * is communicated of.
   * @tparam RI The type of class for redistribution information
   */
  template<class M, class RI>
  struct CommMatrixRowSize
  {
    // Make the default communication policy work.
    typedef typename M::size_type value_type;
    typedef typename M::size_type size_type;

    /**
     * @brief Constructor.
     * @param m_ The matrix whose sparsity pattern is communicated.
     * @param[out] rowsize_ RedistributeInformation object
     */
    CommMatrixRowSize(const M& m_, RI& rowsize_)
      : matrix(m_), rowsize(rowsize_)
    {}
    const M& matrix;
    RI& rowsize;

  };


  /**
   * @brief Utility class to communicate and build the sparsity pattern
   * of a redistributed matrix.
   *
   * @tparam M The type of the matrix that the sparsity pattern
   * is communicated of.
   * @tparam I The type of the index set.
   */
  template<class M, class I>
  struct CommMatrixSparsityPattern
  {
    typedef typename M::size_type size_type;

    /**
     * @brief Constructor for the original side
     * @param m_ The matrix whose sparsity pattern is communicated.
     * @param idxset_ The index set corresponding to the local matrix.
     * @param aggidxset_ The index set corresponding to the redistributed matrix.
     */
    CommMatrixSparsityPattern(const M& m_, const Dune::GlobalLookupIndexSet<I>& idxset_, const I& aggidxset_)
      : matrix(m_), idxset(idxset_), aggidxset(aggidxset_), rowsize()
    {}

    /**
     * @brief Constructor for the redistruted side.
     * @param m_ The matrix whose sparsity pattern is communicated.
     * @param idxset_ The index set corresponding to the local matrix.
     * @param aggidxset_ The index set corresponding to the redistributed matrix.
     * @param rowsize_ The row size for the redistributed owner rows.
     */
    CommMatrixSparsityPattern(const M& m_, const Dune::GlobalLookupIndexSet<I>& idxset_, const I& aggidxset_,
                              const std::vector<typename M::size_type>& rowsize_)
      : matrix(m_), idxset(idxset_), aggidxset(aggidxset_), sparsity(aggidxset_.size()), rowsize(&rowsize_)
    {}

    /**
     * @brief Creates and stores the sparsity pattern of the redistributed matrix.
     *
     * After the pattern is communicated this function can be used.
     * @param m The matrix to build.
     */
    void storeSparsityPattern(M& m)
    {
      // insert diagonal to overlap rows
      typedef typename Dune::GlobalLookupIndexSet<I>::const_iterator IIter;
      typedef typename Dune::OwnerOverlapCopyCommunication<int>::OwnerSet OwnerSet;
      std::size_t nnz=0;
#ifdef DEBUG_REPART
      int rank;

      MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif
      for(IIter i= aggidxset.begin(), end=aggidxset.end(); i!=end; ++i) {
        if(!OwnerSet::contains(i->local().attribute())) {
#ifdef DEBUG_REPART
          std::cout<<rank<<" Inserting diagonal for"<<i->local()<<std::endl;
#endif
          sparsity[i->local()].insert(i->local());
        }

        nnz+=sparsity[i->local()].size();
      }
      assert( aggidxset.size()==sparsity.size());

      if(nnz>0) {
        m.setSize(aggidxset.size(), aggidxset.size(), nnz);
        m.setBuildMode(M::row_wise);
        typename M::CreateIterator citer=m.createbegin();
#ifdef DEBUG_REPART
        std::size_t idx=0;
        bool correct=true;
        Dune::GlobalLookupIndexSet<I> global(aggidxset);
#endif
        typedef typename std::vector<std::set<size_type> >::const_iterator Iter;
        for(Iter i=sparsity.begin(), end=sparsity.end(); i!=end; ++i, ++citer)
        {
          typedef typename std::set<size_type>::const_iterator SIter;
          for(SIter si=i->begin(), send=i->end(); si!=send; ++si)
            citer.insert(*si);
#ifdef DEBUG_REPART
          if(i->find(idx)==i->end()) {
            const typename I::IndexPair* gi=global.pair(idx);
            assert(gi);
            std::cout<<rank<<": row "<<idx<<" is missing a diagonal entry! global="<<gi->global()<<" attr="<<gi->local().attribute()<<" "<<
            OwnerSet::contains(gi->local().attribute())<<
            " row size="<<i->size()<<std::endl;
            correct=false;
          }
          ++idx;
#endif
        }
#ifdef DEBUG_REPART
        if(!correct)
          throw "bla";
#endif
      }
    }

    /**
     * @brief Completes the sparsity pattern of the redistributed matrix with data
     * from copy rows for the novlp case.
     *
     * After the pattern communication this function can be used.
     * @param add_sparsity Sparsity pattern from the copy rows.
     */
    void completeSparsityPattern(std::vector<std::set<size_type> > add_sparsity)
    {
      for (unsigned int i = 0; i != sparsity.size(); ++i) {
        if (add_sparsity[i].size() != 0) {
          typedef std::set<size_type> Set;
          Set tmp_set;
          std::insert_iterator<Set> tmp_insert (tmp_set, tmp_set.begin());
          std::set_union(add_sparsity[i].begin(), add_sparsity[i].end(),
                         sparsity[i].begin(), sparsity[i].end(), tmp_insert);
          sparsity[i].swap(tmp_set);
        }
      }
    }

    const M& matrix;
    typedef Dune::GlobalLookupIndexSet<I> LookupIndexSet;
    const Dune::GlobalLookupIndexSet<I>& idxset;
    const I& aggidxset;
    std::vector<std::set<size_type> > sparsity;
    const std::vector<size_type>* rowsize;
  };

  template<class M, class I>
  struct CommPolicy<CommMatrixSparsityPattern<M,I> >
  {
    typedef CommMatrixSparsityPattern<M,I> Type;

    /**
     *  @brief The indexed type we send.
     * This is the global index indentitfying the column.
     */
    typedef typename I::GlobalIndex IndexedType;

    /** @brief Each row varies in size. */
    typedef VariableSize IndexedTypeFlag;

    static typename M::size_type getSize(const Type& t, std::size_t i)
    {
      if(!t.rowsize)
        return t.matrix[i].size();
      else
      {
        assert((*t.rowsize)[i]>0);
        return (*t.rowsize)[i];
      }
    }
  };

  /**
   * @brief Utility class for comunicating the matrix entries.
   *
   * @tparam M The type of the matrix.
   * @tparam I The type of the ParallelIndexSet.
   */
  template<class M, class I>
  struct CommMatrixRow
  {
    /**
     * @brief Constructor.
     * @param m_ The matrix to communicate the values. That is the local original matrix
     * as the source of the communication and the redistributed at the target of the
     * communication.
     * @param idxset_ The index set for the original matrix.
     * @param aggidxset_ The index set for the redistributed matrix.
     */
    CommMatrixRow(M& m_, const Dune::GlobalLookupIndexSet<I>& idxset_, const I& aggidxset_)
      : matrix(m_), idxset(idxset_), aggidxset(aggidxset_), rowsize()
    {}

    /**
     * @brief Constructor.
     */
    CommMatrixRow(M& m_, const Dune::GlobalLookupIndexSet<I>& idxset_, const I& aggidxset_,
                  std::vector<size_t>& rowsize_)
      : matrix(m_), idxset(idxset_), aggidxset(aggidxset_), rowsize(&rowsize_)
    {}
    /**
     * @brief Sets the non-owner rows correctly as Dirichlet boundaries.
     *
     * This should be called after the communication.
     */
    void setOverlapRowsToDirichlet()
    {
      typedef typename Dune::GlobalLookupIndexSet<I>::const_iterator Iter;
      typedef typename Dune::OwnerOverlapCopyCommunication<int>::OwnerSet OwnerSet;

      for(Iter i= aggidxset.begin(), end=aggidxset.end(); i!=end; ++i)
        if(!OwnerSet::contains(i->local().attribute())) {
          // Set to Dirchlet
          typedef typename M::ColIterator CIter;
          for(CIter c=matrix[i->local()].begin(), cend= matrix[i->local()].end();
              c!= cend; ++c)
          {
            *c=0;
            if(c.index()==i->local()) {
              typedef typename M::block_type::RowIterator RIter;
              for(RIter r=c->begin(), rend=c->end();
                  r != rend; ++r)
                (*r)[r.index()]=1;
            }
          }
        }
    }
    /** @brief The matrix to communicate the values of. */
    M& matrix;
    /** @brief Index set for the original matrix. */
    const Dune::GlobalLookupIndexSet<I>& idxset;
    /** @brief Index set for the redistributed matrix. */
    const I& aggidxset;
    /** @brief row size information for the receiving side. */
    std::vector<size_t>* rowsize; // row sizes differ from sender side in overlap!
  };

  template<class M, class I>
  struct CommPolicy<CommMatrixRow<M,I> >
  {
    typedef CommMatrixRow<M,I> Type;

    /**
     *  @brief The indexed type we send.
     * This is the pair of global index indentitfying the column and the value itself.
     */
    typedef std::pair<typename I::GlobalIndex,typename M::block_type> IndexedType;

    /** @brief Each row varies in size. */
    typedef VariableSize IndexedTypeFlag;

    static std::size_t getSize(const Type& t, std::size_t i)
    {
      if(!t.rowsize)
        return t.matrix[i].size();
      else
      {
        assert((*t.rowsize)[i]>0);
        return (*t.rowsize)[i];
      }
    }
  };

  template<class M, class I, class RI>
  struct MatrixRowSizeGatherScatter
  {
    typedef CommMatrixRowSize<M,RI> Container;

    static const typename M::size_type gather(const Container& cont, std::size_t i)
    {
      return cont.matrix[i].size();
    }
    static void scatter(Container& cont, const typename M::size_type& rowsize, std::size_t i)
    {
      assert(rowsize);
      cont.rowsize.getRowSize(i)=rowsize;
    }

  };

  template<class M, class I, class RI>
  struct MatrixCopyRowSizeGatherScatter
  {
    typedef CommMatrixRowSize<M,RI> Container;

    static const typename M::size_type gather(const Container& cont, std::size_t i)
    {
      return cont.matrix[i].size();
    }
    static void scatter(Container& cont, const typename M::size_type& rowsize, std::size_t i)
    {
      assert(rowsize);
      if (rowsize > cont.rowsize.getCopyRowSize(i))
        cont.rowsize.getCopyRowSize(i)=rowsize;
    }

  };

  template<class M, class I>
  struct MatrixSparsityPatternGatherScatter
  {
    typedef typename I::GlobalIndex GlobalIndex;
    typedef CommMatrixSparsityPattern<M,I> Container;
    typedef typename M::ConstColIterator ColIter;

    static ColIter col;
    static GlobalIndex numlimits;

    static const GlobalIndex& gather(const Container& cont, std::size_t i, std::size_t j)
    {
      if(j==0)
        col=cont.matrix[i].begin();
      else if (col!=cont.matrix[i].end())
        ++col;

      //copy communication: different row sizes for copy rows with the same global index
      //are possible. If all values of current  matrix row are sent, send
      //std::numeric_limits<GlobalIndex>::max()
      //and receiver will ignore it.
      if (col==cont.matrix[i].end()) {
        numlimits = std::numeric_limits<GlobalIndex>::max();
        return numlimits;
      }
      else {
        const typename I::IndexPair* index=cont.idxset.pair(col.index());
        assert(index);
        // Only send index if col is no ghost
        if ( index->local().attribute() != 2)
          return index->global();
        else {
          numlimits = std::numeric_limits<GlobalIndex>::max();
          return numlimits;
        }
      }
    }
    static void scatter(Container& cont, const GlobalIndex& gi, std::size_t i, std::size_t j)
    {
      DUNE_UNUSED_PARAMETER(j);
      try{
        if (gi != std::numeric_limits<GlobalIndex>::max()) {
          const typename I::IndexPair& ip=cont.aggidxset.at(gi);
          assert(ip.global()==gi);
          std::size_t column = ip.local();
          cont.sparsity[i].insert(column);

          typedef typename Dune::OwnerOverlapCopyCommunication<int>::OwnerSet OwnerSet;
          if(!OwnerSet::contains(ip.local().attribute()))
            // preserve symmetry for overlap
            cont.sparsity[column].insert(i);
        }
      }
      catch(Dune::RangeError er) {
        // Entry not present in the new index set. Ignore!
#ifdef DEBUG_REPART
        typedef typename Container::LookupIndexSet GlobalLookup;
        typedef typename GlobalLookup::IndexPair IndexPair;
        typedef typename Dune::OwnerOverlapCopyCommunication<int>::OwnerSet OwnerSet;

        GlobalLookup lookup(cont.aggidxset);
        const IndexPair* pi=lookup.pair(i);
        assert(pi);
        if(OwnerSet::contains(pi->local().attribute())) {
          int rank;
          MPI_Comm_rank(MPI_COMM_WORLD,&rank);
          std::cout<<rank<<cont.aggidxset<<std::endl;
          std::cout<<rank<<": row "<<i<<" (global="<<gi <<") not in index set for owner index "<<pi->global()<<std::endl;
          throw er;
        }
#endif
      }
    }

  };
  template<class M, class I>
  typename MatrixSparsityPatternGatherScatter<M,I>::ColIter MatrixSparsityPatternGatherScatter<M,I>::col;

  template<class M, class I>
  typename MatrixSparsityPatternGatherScatter<M,I>::GlobalIndex MatrixSparsityPatternGatherScatter<M,I>::numlimits;


  template<class M, class I>
  struct MatrixRowGatherScatter
  {
    typedef typename I::GlobalIndex GlobalIndex;
    typedef CommMatrixRow<M,I> Container;
    typedef typename M::ConstColIterator ColIter;
    typedef typename std::pair<GlobalIndex,typename M::block_type> Data;
    static ColIter col;
    static Data datastore;
    static GlobalIndex numlimits;

    static const Data& gather(const Container& cont, std::size_t i, std::size_t j)
    {
      if(j==0)
        col=cont.matrix[i].begin();
      else if (col!=cont.matrix[i].end())
        ++col;
      // copy communication: different row sizes for copy rows with the same global index
      // are possible. If all values of current  matrix row are sent, send
      // std::numeric_limits<GlobalIndex>::max()
      // and receiver will ignore it.
      if (col==cont.matrix[i].end()) {
        numlimits = std::numeric_limits<GlobalIndex>::max();
        datastore = std::make_pair(numlimits,*col);
        return datastore;
      }
      else {
        // convert local column index to global index
        const typename I::IndexPair* index=cont.idxset.pair(col.index());
        assert(index);
        // Store the data to prevent reference to temporary
        // Only send index if col is no ghost
        if ( index->local().attribute() != 2)
          datastore = std::make_pair(index->global(),*col);
        else {
          numlimits = std::numeric_limits<GlobalIndex>::max();
          datastore = std::make_pair(numlimits,*col);
        }
        return datastore;
      }
    }
    static void scatter(Container& cont, const Data& data, std::size_t i, std::size_t j)
    {
      DUNE_UNUSED_PARAMETER(j);
      try{
        if (data.first != std::numeric_limits<GlobalIndex>::max()) {
          typename M::size_type column=cont.aggidxset.at(data.first).local();
          cont.matrix[i][column]=data.second;
        }
      }
      catch(Dune::RangeError er) {
        // This an overlap row and might therefore lack some entries!
      }

    }
  };

  template<class M, class I>
  typename MatrixRowGatherScatter<M,I>::ColIter MatrixRowGatherScatter<M,I>::col;

  template<class M, class I>
  typename MatrixRowGatherScatter<M,I>::Data MatrixRowGatherScatter<M,I>::datastore;

  template<class M, class I>
  typename MatrixRowGatherScatter<M,I>::GlobalIndex MatrixRowGatherScatter<M,I>::numlimits;

  template<typename M, typename C>
  void redistributeSparsityPattern(M& origMatrix, M& newMatrix, C& origComm, C& newComm,
                                   RedistributeInformation<C>& ri)
  {
    typename C::CopySet copyflags;
    typename C::OwnerSet ownerflags;
    typedef typename C::ParallelIndexSet IndexSet;
    typedef RedistributeInformation<C> RI;
    std::vector<typename M::size_type> rowsize(newComm.indexSet().size(), 0);
    std::vector<typename M::size_type> copyrowsize(newComm.indexSet().size(), 0);
    std::vector<typename M::size_type> backwardscopyrowsize(origComm.indexSet().size(), 0);

    // get owner rowsizes
    CommMatrixRowSize<M,RI> commRowSize(origMatrix, ri);
    ri.template redistribute<MatrixRowSizeGatherScatter<M,IndexSet,RI> >(commRowSize,commRowSize);

    origComm.buildGlobalLookup();

    for (std::size_t i=0; i < newComm.indexSet().size(); i++) {
      rowsize[i] = ri.getRowSize(i);
    }
    // get sparsity pattern from owner rows
    CommMatrixSparsityPattern<M,IndexSet>
    origsp(origMatrix, origComm.globalLookup(), newComm.indexSet());
    CommMatrixSparsityPattern<M,IndexSet>
    newsp(origMatrix, origComm.globalLookup(), newComm.indexSet(), rowsize);

    ri.template redistribute<MatrixSparsityPatternGatherScatter<M,IndexSet> >(origsp,newsp);

    // build copy to owner interface to get missing matrix values for novlp case
    if (origComm.getSolverCategory() == SolverCategory::nonoverlapping) {
      RemoteIndices<IndexSet> *ris = new RemoteIndices<IndexSet>(origComm.indexSet(),
                                                                 newComm.indexSet(),
                                                                 origComm.communicator());
      ris->template rebuild<true>();

      ri.getInterface().free();
      ri.getInterface().build(*ris,copyflags,ownerflags);

      // get copy rowsizes
      CommMatrixRowSize<M,RI> commRowSize_copy(origMatrix, ri);
      ri.template redistribute<MatrixCopyRowSizeGatherScatter<M,IndexSet,RI> >(commRowSize_copy,
                                                                               commRowSize_copy);

      for (std::size_t i=0; i < newComm.indexSet().size(); i++) {
        copyrowsize[i] = ri.getCopyRowSize(i);
      }
      //get copy rowsizes for sender
      ri.redistributeBackward(backwardscopyrowsize,copyrowsize);
      for (std::size_t i=0; i < origComm.indexSet().size(); i++) {
        ri.getBackwardsCopyRowSize(i) = backwardscopyrowsize[i];
      }

      // get sparsity pattern from copy rows
      CommMatrixSparsityPattern<M,IndexSet> origsp_copy(origMatrix,
                                                        origComm.globalLookup(),
                                                        newComm.indexSet(),
                                                        backwardscopyrowsize);
      CommMatrixSparsityPattern<M,IndexSet> newsp_copy(origMatrix, origComm.globalLookup(),
                                                       newComm.indexSet(), copyrowsize);
      ri.template redistribute<MatrixSparsityPatternGatherScatter<M,IndexSet> >(origsp_copy,
                                                                                newsp_copy);

      newsp.completeSparsityPattern(newsp_copy.sparsity);
      newsp.storeSparsityPattern(newMatrix);
    }
    else
      newsp.storeSparsityPattern(newMatrix);

#ifdef DUNE_ISTL_WITH_CHECKING
    // Check for symmetry
    int ret=0;
    typedef typename M::ConstRowIterator RIter;
    for(RIter row=newMatrix.begin(), rend=newMatrix.end(); row != rend; ++row) {
      typedef typename M::ConstColIterator CIter;
      for(CIter col=row->begin(), cend=row->end(); col!=cend; ++col)
      {
        try{
          newMatrix[col.index()][row.index()];
        }catch(Dune::ISTLError e) {
          std::cerr<<newComm.communicator().rank()<<": entry ("
                   <<col.index()<<","<<row.index()<<") missing! for symmetry!"<<std::endl;
          ret=1;

        }

      }
    }

    if(ret)
      DUNE_THROW(ISTLError, "Matrix not symmetric!");
#endif
  }

  template<typename M, typename C>
  void redistributeMatrixEntries(M& origMatrix, M& newMatrix, C& origComm, C& newComm,
                                 RedistributeInformation<C>& ri)
  {
    typedef typename C::ParallelIndexSet IndexSet;
    typename C::OwnerSet ownerflags;
    std::vector<typename M::size_type> rowsize(newComm.indexSet().size(), 0);
    std::vector<typename M::size_type> copyrowsize(newComm.indexSet().size(), 0);
    std::vector<typename M::size_type> backwardscopyrowsize(origComm.indexSet().size(), 0);

    for (std::size_t i=0; i < newComm.indexSet().size(); i++) {
      rowsize[i] = ri.getRowSize(i);
      if (origComm.getSolverCategory() == SolverCategory::nonoverlapping) {
        copyrowsize[i] = ri.getCopyRowSize(i);
      }
    }

    for (std::size_t i=0; i < origComm.indexSet().size(); i++)
      if (origComm.getSolverCategory() == SolverCategory::nonoverlapping)
        backwardscopyrowsize[i] = ri.getBackwardsCopyRowSize(i);


    if (origComm.getSolverCategory() == SolverCategory::nonoverlapping) {
      // fill sparsity pattern from copy rows
      CommMatrixRow<M,IndexSet> origrow_copy(origMatrix, origComm.globalLookup(),
                                             newComm.indexSet(), backwardscopyrowsize);
      CommMatrixRow<M,IndexSet> newrow_copy(newMatrix, origComm.globalLookup(),
                                            newComm.indexSet(),copyrowsize);
      ri.template redistribute<MatrixRowGatherScatter<M,IndexSet> >(origrow_copy,
                                                                    newrow_copy);
      ri.getInterface().free();
      RemoteIndices<IndexSet> *ris = new RemoteIndices<IndexSet>(origComm.indexSet(),
                                                                 newComm.indexSet(),
                                                                 origComm.communicator());
      ris->template rebuild<true>();
      ri.getInterface().build(*ris,ownerflags,ownerflags);
    }

    CommMatrixRow<M,IndexSet>
    origrow(origMatrix, origComm.globalLookup(), newComm.indexSet());
    CommMatrixRow<M,IndexSet>
    newrow(newMatrix, origComm.globalLookup(), newComm.indexSet(),rowsize);
    ri.template redistribute<MatrixRowGatherScatter<M,IndexSet> >(origrow,newrow);
    if (origComm.getSolverCategory() != static_cast<int>(SolverCategory::nonoverlapping))
      newrow.setOverlapRowsToDirichlet();
  }

  /**
   * @brief Redistribute a matrix according to given domain decompositions.
   *
   * All the parameters for this function can be obtained by calling
   * graphRepartition with the graph of the original matrix.
   *
   * @param origMatrix The matrix on the original partitioning.
   * @param newMatrix An empty matrix to store the new redistributed matrix in.
   * @param origComm The parallel information of the original partitioning.
   * @param newComm The parallel information of the new partitioning.
   * @param ri The remote index information between the original and the new partitioning.
   * Upon exit of this method it will be prepared for copying from owner to owner vertices
   * for data redistribution.
   * @tparam M The matrix type. It is assumed to be sparse. E.g. BCRSMatrix.
   * @tparam C The type of the parallel information, see OwnerOverlapCopyCommunication.
   */
  template<typename M, typename C>
  void redistributeMatrix(M& origMatrix, M& newMatrix, C& origComm, C& newComm,
                          RedistributeInformation<C>& ri)
  {
    ri.setNoRows(newComm.indexSet().size());
    ri.setNoCopyRows(newComm.indexSet().size());
    ri.setNoBackwardsCopyRows(origComm.indexSet().size());
    redistributeSparsityPattern(origMatrix, newMatrix, origComm, newComm, ri);
    redistributeMatrixEntries(origMatrix, newMatrix, origComm, newComm, ri);
  }
#endif

template<typename M>
  void redistributeMatrixEntries(M& origMatrix, M& newMatrix,
                                 Dune::Amg::SequentialInformation& origComm,
                                 Dune::Amg::SequentialInformation& newComm,
                                 RedistributeInformation<Dune::Amg::SequentialInformation>& ri)
  {
    DUNE_THROW(InvalidStateException, "Trying to redistribute in sequential program!");
  }
  template<typename M>
  void redistributeMatrix(M& origMatrix, M& newMatrix,
                          Dune::Amg::SequentialInformation& origComm,
                          Dune::Amg::SequentialInformation& newComm,
                          RedistributeInformation<Dune::Amg::SequentialInformation>& ri)
  {
    DUNE_THROW(InvalidStateException, "Trying to redistribute in sequential program!");
  }
}
#endif