dune-fem 2.12-git
Loading...
Searching...
No Matches
istlmatrix.hh
Go to the documentation of this file.
1#ifndef DUNE_FEM_ISTLMATRIXWRAPPER_HH
2#define DUNE_FEM_ISTLMATRIXWRAPPER_HH
3
4#if HAVE_DUNE_ISTL
5
6//#define USE_IBCRS_MATRIX
7
8//- system includes
9#include <vector>
10#include <iostream>
11#include <fstream>
12#include <algorithm>
13#include <set>
14#include <map>
15#include <string>
16
17//- Dune common includes
20
21//- Dune istl includes
22#include <dune/istl/bvector.hh>
24#include <dune/istl/experimental/bcrsmatrix.hh>
26
27//- Dune fem includes
37
41
42namespace Dune
43{
44
45 namespace Fem
46 {
47
48
50 template< class MatrixObject >
51 class ISTLLocalMatrix;
52
53 template <class DomainSpaceImp, class RangeSpaceImp,
56 class ISTLMatrixObject;
57
59 // --ISTLMatrixHandle
61 template <class LittleBlockType, class RowDiscreteFunctionImp, class ColDiscreteFunctionImp = RowDiscreteFunctionImp>
62 class ImprovedBCRSMatrix :
63#ifdef USE_IBCRS_MATRIX
64 public Dune::Experimental::BCRSMatrix<LittleBlockType>
65#else
66 public BCRSMatrix<LittleBlockType>
67#endif
68 {
69 friend struct MatrixDimension<ImprovedBCRSMatrix>;
70 public:
71 typedef RowDiscreteFunctionImp RowDiscreteFunctionType;
72 typedef ColDiscreteFunctionImp ColDiscreteFunctionType;
73
74#ifdef USE_IBCRS_MATRIX
76#else
77 typedef BCRSMatrix<LittleBlockType> BaseType;
78#endif
80 typedef BaseType MatrixBaseType;
81 typedef typename BaseType :: RowIterator RowIteratorType ;
82 typedef typename BaseType :: ColIterator ColIteratorType ;
83
84 typedef ImprovedBCRSMatrix< LittleBlockType, RowDiscreteFunctionImp, ColDiscreteFunctionImp > ThisType;
85
86 typedef typename BaseType :: size_type size_type;
87
88 //===== type definitions and constants
89
91 typedef typename BaseType::field_type field_type;
92
94 typedef typename BaseType::block_type block_type;
95
97 typedef typename BaseType:: allocator_type allocator_type;
98
100 typedef typename BaseType :: row_type row_type;
101
103 typedef typename BaseType :: ColIterator ColIterator;
104
106 typedef typename BaseType :: ConstColIterator ConstColIterator;
107
109 typedef typename BaseType :: RowIterator RowIterator;
110
112 typedef typename BaseType :: ConstRowIterator ConstRowIterator;
113
115 typedef typename ColDiscreteFunctionType :: DiscreteFunctionSpaceType RangeSpaceType;
116
118 typedef typename RowDiscreteFunctionType :: DofStorageType RowBlockVectorType;
119
121 typedef typename ColDiscreteFunctionType :: DofStorageType ColBlockVectorType;
122
124 typedef typename RangeSpaceType :: GridType :: Traits :: Communication CommunicationType ;
125
126 typedef typename BaseType :: BuildMode BuildMode ;
127
128#ifdef USE_IBCRS_MATRIX
129 struct ReversedIterator : public std::reverse_iterator<ConstRowIterator>
130 {
131 typedef std::reverse_iterator<ConstRowIterator> IterBaseType;
132 ReversedIterator( const ConstRowIterator& it )
133 : IterBaseType( it )
134 {}
135
136 ReversedIterator( ConstRowIterator&& it )
137 : IterBaseType( std::move(it) )
138 {}
139
140 //ReversedIterator& operator --(int) { return this->operator++(int(0)); }
141
142 // provide reversed index method
143 size_type index() const { return std::prev(this->base()).index(); }
144
145 void isNewIterator() const {}
146 };
147
148 ReversedIterator beforeBegin() const { return ReversedIterator( this->begin() ); }
149 ReversedIterator beforeEnd() const { return ReversedIterator( this->end() ); }
150#else
151 using SlicedConstIterator = ConstRowIterator;
152#endif
153
154 public:
156 ImprovedBCRSMatrix(size_type rows, size_type cols, size_type nnz, double overflowFraction) :
157 BaseType (rows, cols, nnz, overflowFraction, BaseType::implicit)
158 {}
159
161 ImprovedBCRSMatrix(size_type rows, size_type cols, size_type nz = 0 ) :
162 BaseType (rows, cols, BaseType :: row_wise)
163 {}
164
166 ImprovedBCRSMatrix( ) :
167 BaseType ()
168 {}
169
171 ImprovedBCRSMatrix(const ImprovedBCRSMatrix& org) :
172 BaseType(org)
173 {}
174
175 RowIterator slicedRowIt( size_type row )
176 {
177 return this->begin() + row;
178 }
179
180 ConstRowIterator slicedRowIt( size_type row ) const
181 {
182 return this->begin() + row;
183 }
184
185 ConstRowIterator slicedBegin( size_type row ) const { return slicedRowIt( row ); }
186 ConstRowIterator slicedEnd( size_type row ) const { return slicedRowIt( row ); }
187
188 std::pair< size_type, size_type > sliceBeginEnd( const size_type thread, const size_type numThreads ) const
189 {
190 const size_type sliceSize = this->N() / numThreads ;
191 const size_type sliceBegin = thread * sliceSize ;
192 const size_type sliceEnd = ( thread == numThreads-1 ) ? this->N() : (sliceBegin + sliceSize) ;
193 return std::make_pair( sliceBegin, sliceEnd );
194 }
195
196 protected:
197 template <class X, class Y, bool isMV>
198 void mvThreadedImpl( [[maybe_unused]] const field_type& alpha,
199 const X& x, Y& y, std::integral_constant<bool, isMV> ) const
200 {
201 auto doMV = [this, &alpha, &x, &y] ()
202 {
203 // this is simply to avoid warnings since
204 // there exist no maybe_unused for lambda captures
205 if constexpr ( isMV )
206 {
207 [[maybe_unused]] field_type a = alpha;
208 }
209
210 const auto slice = sliceBeginEnd( MPIManager::thread(), MPIManager::numThreads() );
211 const ConstRowIterator endi = slicedEnd( slice.second );
212 for (ConstRowIterator i = slicedBegin(slice.first); i!=endi; ++i)
213 {
214 if constexpr ( isMV )
215 y[i.index()] = 0;
216
217 ConstColIterator endj = (*i).end();
218 for (ConstColIterator j=(*i).begin(); j!=endj; ++j)
219 {
220 auto&& xj = Dune::Impl::asVector(x[j.index()]);
221 auto&& yi = Dune::Impl::asVector(y[i.index()]);
222 if constexpr ( isMV )
223 Dune::Impl::asMatrix(*j).umv(xj, yi);
224 else
225 Dune::Impl::asMatrix(*j).usmv(alpha, xj, yi);
226 }
227 }
228 };
229
230 try {
231 // execute in parallel
232 MPIManager :: run ( doMV );
233 }
234 catch ( const SingleThreadModeError& e )
235 {
236 // serial version
237 if constexpr ( isMV )
238 this->mv( x, y );
239 else
240 {
241 DUNE_THROW(SingleThreadModeError,"ImprovedBCRSMatrix::usmvThreaded: Cannot recover from threading error. Disable threading!");
242 // this->usmv( alpha, x, y );
243 }
244 }
245 }
246
247 public:
248 template <class X, class Y>
249 void usmvThreaded( const field_type& alpha, const X& x, Y& y ) const
250 {
251 mvThreadedImpl(alpha, x, y, std::false_type() );
252 }
253
254 template <class X, class Y>
255 void mvThreaded( const X& x, Y& y ) const
256 {
257 mvThreadedImpl(1.0, x, y, std::true_type() );
258 }
259
260 template < class SparsityPattern >
261 void createEntries(const SparsityPattern& sparsityPattern)
262 {
263 const auto spEnd = sparsityPattern.end();
264
265 // insert map of indices into matrix
266 auto endcreate = this->createend();
267 for(auto create = this->createbegin(); create != endcreate; ++create)
268 {
269 const auto row = sparsityPattern.find( create.index() );
270 // if a row is empty then do nothing
271 if( row == spEnd ) continue;
272
273 // insert all indices for this row
274 for ( const auto& col : row->second )
275 create.insert( col );
276 }
277 }
278
280 void clear()
281 {
282 const auto endrow = this->end();
283 for (auto row = this->begin(); row !=endrow; ++row)
284 {
285 const auto colend = (*row).end();
286 for (auto col = (*row).begin(); col != colend; ++col )
287 *col = 0;
288 }
289 }
290
292 void unitRow( const size_t row )
293 {
294 block_type idBlock( 0 );
295 for (int i = 0; i < idBlock.rows; ++i)
296 idBlock[i][i] = 1.0;
297
298 auto matRow = slicedRowIt( row );
299 assert( matRow != this->end() );
300 auto colIt = (*matRow).begin();
301 const auto& colEndIt = (*matRow).end();
302 for (; colIt != colEndIt; ++colIt)
303 {
304 if( colIt.index() == row )
305 *colIt = idBlock;
306 else
307 *colIt = 0.0;
308 }
309 }
310
312 template <class HangingNodesType>
313 void setup(ThisType& oldMatrix, const HangingNodesType& hangingNodes)
314 {
315 // necessary because element traversal not necessarily is in ascending order
316 typedef std::set< std::pair<int, block_type> > LocalEntryType;
317 typedef std::map< int , LocalEntryType > EntriesType;
318 EntriesType entries;
319
320 // map of indices
322 // not insert map of indices into matrix
323 auto rowend = oldMatrix.end();
324 for(auto it = oldMatrix.begin(); it != rowend; ++it)
325 {
326 const auto row = it.index();
327 auto& localIndices = indices[ row ];
328
329 if( hangingNodes.isHangingNode( row ) )
330 {
331 // insert columns into other columns
332 const auto& cols = hangingNodes.associatedDofs( row );
333 const auto colSize = cols.size();
334 for(auto i=0; i<colSize; ++i)
335 {
336 assert( ! hangingNodes.isHangingNode( cols[i].first ) );
337
338 // get local indices of col
339 auto& localColIndices = indices[ cols[i].first ];
340 auto& localEntry = entries[ cols[i].first ];
341
342 // copy from old matrix
343 auto endj = (*it).end();
344 for (auto j= (*it).begin(); j!=endj; ++j)
345 {
346 localColIndices.insert( j.index () );
347 localEntry.insert( std::make_pair( j.index(), (cols[i].second * (*j)) ));
348 }
349 }
350
351 // insert diagonal and hanging columns
352 localIndices.insert( row );
353 for(auto i=0; i<colSize; ++i)
354 localIndices.insert( cols[i].first );
355 }
356 else
357 {
358 // copy from old matrix
359 auto endj = (*it).end();
360 for (auto j= (*it).begin(); j!=endj; ++j)
361 localIndices.insert( j.index () );
362 }
363 }
364
365 // create matrix from entry map
366 createEntries( indices );
367
368 // not insert map of indices into matrix
369 auto rowit = oldMatrix.begin();
370
371 auto endcreate = this->end();
372 for(auto create = this->begin(); create != endcreate; ++create, ++rowit )
373 {
374 assert( rowit != oldMatrix.end() );
375
376 const auto row = create.index();
377 if( hangingNodes.isHangingNode( row ) )
378 {
379 const auto& cols = hangingNodes.associatedDofs( row );
380
382 // only working for block size 1 ath the moment
383 assert( block_type :: rows == 1 );
384 // insert columns into map
385 const auto colSize = cols.size();
386 for( auto i=0; i<colSize; ++i)
387 colMap[ cols[i].first ] = -cols[i].second;
388 // insert diagonal into map
389 colMap[ row ] = 1;
390
391 auto endj = (*create).end();
392 for (auto j= (*create).begin(); j!=endj; ++j)
393 {
394 assert( colMap.find( j.index() ) != colMap.end() );
395 (*j) = colMap[ j.index() ];
396 }
397 }
398 // if entries are equal, just copy
399 else if ( entries.find( row ) == entries.end() )
400 {
401 auto colit = (*rowit).begin();
402 auto endj = (*create).end();
403 for (auto j= (*create).begin(); j!=endj; ++j, ++colit )
404 {
405 assert( colit != (*rowit).end() );
406 (*j) = (*colit);
407 }
408 }
409 else
410 {
412
413 {
414 auto colend = (*rowit).end();
415 for(auto colit = (*rowit).begin(); colit != colend; ++colit)
416 oldCols[ colit.index() ] = 0;
417 }
418
419 auto entry = entries.find( row );
420 assert( entry != entries.end ());
421
422 {
423 auto endcol = (*entry).second.end();
424 for( auto co = (*entry).second.begin(); co != endcol; ++co)
425 oldCols[ (*co).first ] = 0;
426 }
427
428 {
429 auto colend = (*rowit).end();
430 for(auto colit = (*rowit).begin(); colit != colend; ++colit)
431 oldCols[ colit.index() ] += (*colit);
432 }
433
434 {
435 auto endcol = (*entry).second.end();
436 for( auto co = (*entry).second.begin(); co != endcol; ++co)
437 oldCols[ (*co).first ] += (*co).second;
438 }
439
440 auto endj = (*create).end();
441 for (auto j= (*create).begin(); j!=endj; ++j )
442 {
443 auto colEntry = oldCols.find( j.index() );
444 if( colEntry != oldCols.end() )
445 (*j) = (*colEntry).second;
446 else
447 abort();
448 }
449 }
450 }
451 }
452
454 void extractDiagonal( ColBlockVectorType& diag ) const
455 {
456 const auto endi = this->end();
457 for (auto i = this->begin(); i!=endi; ++i)
458 {
459 // get diagonal entry of matrix
460 const auto row = i.index();
461 auto entry = (*i).find( row );
462 const LittleBlockType& block = (*entry);
463 enum { blockSize = LittleBlockType :: rows };
464 for( auto l=0; l<blockSize; ++l )
465 diag[ row ][ l ] = block[ l ][ l ];
466 }
467 }
468
471 field_type operator()(const std::size_t row, const std::size_t col) const
472 {
473 const std::size_t blockRow(row/(LittleBlockType :: rows));
474 const std::size_t localRowIdx(row%(LittleBlockType :: rows));
475 const std::size_t blockCol(col/(LittleBlockType :: cols));
476 const std::size_t localColIdx(col%(LittleBlockType :: cols));
477
478 const auto& matrixRow(this->operator[](blockRow));
479 auto entry = matrixRow.find( blockCol );
480 const LittleBlockType& block = (*entry);
481 return block[localRowIdx][localColIdx];
482 }
483
486 void set(const std::size_t row, const std::size_t col, field_type value)
487 {
488 const std::size_t blockRow(row/(LittleBlockType :: rows));
489 const std::size_t localRowIdx(row%(LittleBlockType :: rows));
490 const std::size_t blockCol(col/(LittleBlockType :: cols));
491 const std::size_t localColIdx(col%(LittleBlockType :: cols));
492
493 auto& matrixRow(this->operator[](blockRow));
494 auto entry = matrixRow.find( blockCol );
495 LittleBlockType& block = (*entry);
496 block[localRowIdx][localColIdx] = value;
497 }
498
500 void print(std::ostream& s=std::cout, unsigned int offset=0) const
501 {
502 s.precision( 6 );
503 const auto endi=this->end();
504 for (auto i=this->begin(); i!=endi; ++i)
505 {
506 const auto endj = (*i).end();
507 for (auto j=(*i).begin(); j!=endj; ++j)
508 if( (*j).infinity_norm() > 1.e-15)
509 s << i.index()+offset << " " << j.index()+offset << " " << *j << std::endl;
510 }
511 }
512 };
513
514
515
516 // ISTLLocalMatrixTraits
517 // ---------------------
518
519 template< class MatrixObject >
520 struct ISTLLocalMatrixTraits
521 {
522 typedef typename MatrixObject::DomainSpaceType DomainSpaceType;
523 typedef typename MatrixObject::RangeSpaceType RangeSpaceType;
524 typedef typename DomainSpaceType::RangeFieldType RangeFieldType;
525
526 typedef ISTLLocalMatrix< MatrixObject > LocalMatrixType;
527 typedef typename MatrixObject::MatrixType::block_type LittleBlockType;
528 };
529
530
531 // ISTLLocalMatrix
532 // ---------------
533
534 template< class MatrixObject >
535 class ISTLLocalMatrix
536 : public LocalMatrixDefault< ISTLLocalMatrixTraits< MatrixObject > >
537 {
538 public:
540 typedef LocalMatrixDefault< ISTLLocalMatrixTraits< MatrixObject > > BaseType;
541
543 typedef MatrixObject MatrixObjectType;
545 typedef typename MatrixObjectType::MatrixType MatrixType;
547 typedef typename MatrixType::block_type LittleBlockType;
548 // type of row and column indices
549 typedef typename MatrixType :: size_type size_type;
550
551 typedef typename MatrixObjectType::DomainSpaceType DomainSpaceType;
552 typedef typename MatrixObjectType::RangeSpaceType RangeSpaceType;
553
554 typedef typename MatrixObjectType::DomainEntityType DomainEntityType;
555 typedef typename MatrixObjectType::RangeEntityType RangeEntityType;
556
558 typedef typename DomainSpaceType::RangeFieldType DofType;
559 typedef typename MatrixType::row_type RowType;
560
562 typedef typename DomainSpaceType::BlockMapperType ColMapperType;
564 typedef typename RangeSpaceType::BlockMapperType RowMapperType;
565
566 static const int littleCols = MatrixObjectType::littleCols;
567 static const int littleRows = MatrixObjectType::littleRows;
568
569 typedef typename MatrixType::size_type Index;
570
574 [[deprecated("Use TemporaryLocalMatrix,LocalContribution and {get,add,set}LocalMatrix")]]
575 ISTLLocalMatrix ( const MatrixObjectType& mObj, const DomainSpaceType& domainSpace, const RangeSpaceType& rangeSpace )
576 : BaseType( domainSpace, rangeSpace ),
577 rowMapper_( rangeSpace.blockMapper() ),
578 colMapper_( domainSpace.blockMapper() ),
579 numRows_( rowMapper_.maxNumDofs() ),
580 numCols_( colMapper_.maxNumDofs() ),
581 matrixObj_( mObj )
582 {}
583
587 [[deprecated("Use TemporaryLocalMatrix,LocalContribution and {get,add,set}LocalMatrix")]]
588 ISTLLocalMatrix ( const ISTLLocalMatrix& org )
589 : BaseType( org ),
590 rowMapper_(org.rowMapper_),
591 colMapper_(org.colMapper_),
592 numRows_( org.numRows_ ),
593 numCols_( org.numCols_ ),
594 matrices_(org.matrices_),
595 matrixObj_(org.matrixObj_)
596 {}
597
599 void init ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity )
600 {
601 // initialize base functions sets
602 BaseType :: init ( domainEntity, rangeEntity );
603
604 numRows_ = rowMapper_.numDofs( rangeEntity );
605 numCols_ = colMapper_.numDofs( domainEntity );
606
607 // resize matrix pointer storage for new row/col numbers
608 matrices_.resize( numRows_ );
609 for( auto& row : matrices_ )
610 {
611 row.resize( numCols_, nullptr );
612 }
613
614 if( matrixObj_.implicitModeActive() )
615 {
616 auto blockAccess = [ this ] ( const std::pair< Index, Index > &index ) -> LittleBlockType&
617 {
618 return matrixObj_.matrix().entry( index.first, index.second );
619 };
620 initBlocks( blockAccess, domainEntity, rangeEntity );
621 }
622 else
623 {
624 auto blockAccess = [ this ] ( const std::pair< Index, Index > &index ) -> LittleBlockType&
625 {
626 return matrixObj_.matrix()[ index.first ][ index.second ];
627 };
628 initBlocks( blockAccess, domainEntity, rangeEntity );
629 }
630 }
631
632 template <class BlockAccess>
633 void initBlocks( BlockAccess& blockAccess, const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity )
634 {
635 auto functor = [ this, &blockAccess ] ( std::pair< int, int > local, const std::pair< Index, Index > &index )
636 {
637 matrices_[ local.first ][ local.second ] = &blockAccess( index );
638 };
639
640 rowMapper_.mapEach( rangeEntity, makePairFunctor( colMapper_, domainEntity, functor ) );
641 }
642
643 private:
644 // check whether given (row,col) pair is valid
645 void check(int localRow, int localCol) const
646 {
647#ifndef NDEBUG
648 const std::size_t row = (int) localRow / littleRows;
649 const std::size_t col = (int) localCol / littleCols;
650 const int lRow = localRow%littleRows;
651 const int lCol = localCol%littleCols;
652 assert( row < matrices_.size() ) ;
653 assert( col < matrices_[row].size() );
654 assert( lRow < littleRows );
655 assert( lCol < littleCols );
656#endif
657 }
658
659 DofType& getValue(const int localRow, const int localCol)
660 {
661 const int row = (int) localRow / littleRows;
662 const int col = (int) localCol / littleCols;
663 const int lRow = localRow%littleRows;
664 const int lCol = localCol%littleCols;
665 return (*matrices_[row][col])[lRow][lCol];
666 }
667
668 public:
669 const DofType get(const int localRow, const int localCol) const
670 {
671 const int row = (int) localRow / littleRows;
672 const int col = (int) localCol / littleCols;
673 const int lRow = localRow%littleRows;
674 const int lCol = localCol%littleCols;
675 return (*matrices_[row][col])[lRow][lCol];
676 }
677
678 void scale (const DofType& scalar)
679 {
680 const size_type nrows = matrices_.size();
681 for(size_type i=0; i<nrows; ++i)
682 {
683 const size_type ncols = matrices_[i].size();
684 for(size_type j=0; j<ncols; ++j)
685 {
686 (*matrices_[i][j]) *= scalar;
687 }
688 }
689 }
690
691 void add(const int localRow, const int localCol , const DofType value)
692 {
693#ifndef NDEBUG
694 check(localRow,localCol);
695#endif
696 getValue(localRow,localCol) += value;
697 }
698
699 void set(const int localRow, const int localCol , const DofType value)
700 {
701#ifndef NDEBUG
702 check(localRow,localCol);
703#endif
704 getValue(localRow,localCol) = value;
705 }
706
708 void unitRow(const int localRow)
709 {
710 const int row = (int) localRow / littleRows;
711 const int lRow = localRow%littleRows;
712
713 // clear row
714 doClearRow( row, lRow );
715
716 // set diagonal entry to 1
717 (*matrices_[row][row])[lRow][lRow] = 1;
718 }
719
721 void clear ()
722 {
723 const size_type nrows = matrices_.size();
724 for(size_type i=0; i<nrows; ++i)
725 {
726 const size_type ncols = matrices_[i].size();
727 for(size_type j=0; j<ncols; ++j)
728 {
729 (*matrices_[i][j]) = (DofType) 0;
730 }
731 }
732 }
733
735 void clearRow ( const int localRow )
736 {
737 const int row = (int) localRow / littleRows;
738 const int lRow = localRow%littleRows;
739
740 // clear the row
741 doClearRow( row, lRow );
742 }
743
745 void resort ()
746 {}
747
748 protected:
750 void doClearRow ( const int row, const int lRow )
751 {
752 // get number of columns
753 const auto col = this->columns();
754 for(auto localCol=0; localCol<col; ++localCol)
755 {
756 const int col = (int) localCol / littleCols;
757 const int lCol = localCol%littleCols;
758 (*matrices_[row][col])[lRow][lCol] = 0;
759 }
760 }
761
762 private:
763 // special mapper omitting block size
764 const RowMapperType& rowMapper_;
765 const ColMapperType& colMapper_;
766
767 // number of local matrices
768 int numRows_;
769 int numCols_;
770
771 // dynamic matrix with pointers to block matrices
773
774 // matrix to build
775 const MatrixObjectType& matrixObj_;
776 };
777
778
780 template <class DomainSpaceImp, class RangeSpaceImp, class DomainBlock, class RangeBlock >
781 class ISTLMatrixObject
782 {
783 public:
785 typedef DomainSpaceImp DomainSpaceType;
787 typedef RangeSpaceImp RangeSpaceType;
788
790 typedef ISTLMatrixObject< DomainSpaceImp, RangeSpaceImp, DomainBlock, RangeBlock > ThisType;
791 typedef ThisType PreconditionMatrixType;
792
793 typedef typename DomainSpaceType::GridType GridType;
794
795 typedef typename RangeSpaceType :: EntityType RangeEntityType ;
796 typedef typename DomainSpaceType :: EntityType DomainEntityType ;
797
798 enum { littleCols = DomainSpaceType :: localBlockSize };
799 enum { littleRows = RangeSpaceType :: localBlockSize };
800
801 typedef FieldMatrix<typename DomainSpaceType :: RangeFieldType, littleRows, littleCols> LittleBlockType;
802 typedef LittleBlockType block_type;
803 typedef LittleBlockType MatrixBlockType;
804
805 typedef ISTLBlockVectorDiscreteFunction< RangeSpaceType, RangeBlock > RowDiscreteFunctionType;
806 typedef ISTLBlockVectorDiscreteFunction< DomainSpaceType, DomainBlock > ColumnDiscreteFunctionType;
807
808 typedef typename RowDiscreteFunctionType :: DofStorageType RowBlockVectorType;
809 typedef typename ColumnDiscreteFunctionType :: DofStorageType ColumnBlockVectorType;
810
811 typedef typename RangeSpaceType :: BlockMapperType RowMapperType;
812 typedef typename DomainSpaceType :: BlockMapperType ColMapperType;
813
815 typedef ImprovedBCRSMatrix< LittleBlockType , ColumnDiscreteFunctionType , RowDiscreteFunctionType > MatrixType;
816 typedef ISTLParallelMatrixAdapterInterface< MatrixType > MatrixAdapterType;
817
819 typedef ISTLLocalMatrix<ThisType> ObjectType;
820 friend class ISTLLocalMatrix<ThisType>;
821
822 typedef ThisType LocalMatrixFactoryType;
823 typedef ObjectStack< LocalMatrixFactoryType > LocalMatrixStackType;
825 typedef LocalMatrixWrapper< LocalMatrixStackType > LocalMatrixType;
826 typedef ColumnObject< ThisType > LocalColumnObjectType;
827
828 protected:
829 const DomainSpaceType& domainSpace_;
830 const RangeSpaceType& rangeSpace_;
831
832 // special row mapper
833 RowMapperType& rowMapper_;
834 // special col mapper
835 ColMapperType& colMapper_;
836
837 int size_;
838 int sequence_;
839
840 mutable std::unique_ptr< MatrixType > matrix_;
841
842 mutable LocalMatrixStackType localMatrixStack_;
843
844 mutable std::unique_ptr< MatrixAdapterType > matrixAdap_;
845 // overflow fraction for implicit build mode
846 const double overflowFraction_;
847 const bool threading_ ;
848
849 ISTLSolverParameter param_;
850
853 public:
854 ISTLMatrixObject(const ISTLMatrixObject&) = delete;
855
859 ISTLMatrixObject ( const DomainSpaceType &domainSpace, const RangeSpaceType &rangeSpace, const ISTLSolverParameter& param = ISTLSolverParameter() ) :
860 domainSpace_(domainSpace)
861 , rangeSpace_(rangeSpace)
862 , rowMapper_( rangeSpace.blockMapper() )
863 , colMapper_( domainSpace.blockMapper() )
864 , size_(-1)
865 , sequence_(-1)
866 , localMatrixStack_( *this )
867 , overflowFraction_( param.overflowFraction() )
868 , threading_( param.threading() )
869 , param_( param )
870 {}
871
872 protected:
875 MatrixType& matrix() const
876 {
877 assert( matrix_ );
878 return *matrix_;
879 }
880
881 public:
882 bool threading() const { return threading_; }
883
884 void printTexInfo(std::ostream& out) const
885 {
886 out << "ISTL MatrixObj: ";
887 out << "\\\\ \n";
888 }
889
891 std::string preconditionName() const
892 {
893 return "";
894 }
895
896 void createMatrixAdapter ( const ISTLSolverParameter& param ) const
897 {
898 if( !matrixAdap_ )
899 {
900 matrixAdap_ = ISTLMatrixAdapterFactory< ThisType > :: matrixAdapter( *this, param );
901 }
902 assert( matrixAdap_ );
903 }
904
906 MatrixAdapterType& matrixAdapter( const ISTLSolverParameter& parameter ) const
907 {
908 const ISTLSolverParameter* param = dynamic_cast< const ISTLSolverParameter* > (&parameter);
909 if( param )
910 createMatrixAdapter( *param );
911 else
912 {
913 ISTLSolverParameter newparam( parameter );
914 createMatrixAdapter( newparam );
915 }
916
917 finalizeAssembly();
918 return *matrixAdap_;
919 }
920
922 MatrixAdapterType& matrixAdapter() const
923 {
924 return matrixAdapter( param_ );
925 }
926
927 public:
928 MatrixType& exportMatrix() const
929 {
930 finalizeAssembly();
931 return matrix();
932 }
933
934 bool implicitModeActive() const
935 {
936 // implicit build mode is only active when the
937 // build mode of the matrix is implicit and the
938 // matrix is currently being build
939
940#ifndef USE_IBCRS_MATRIX
941 if( matrix().buildMode() == MatrixType::implicit && matrix().buildStage() == MatrixType::building )
942 return true;
943 else
944#endif
945 return false;
946 }
947
948 void finalizeAssembly() const
949 {
950 // finalize build mode
951 const_cast< ThisType& > (*this).compress();
952 }
953
954 // compress matrix if not already done before and only in implicit build mode
955 void compress( )
956 {
957 if( implicitModeActive() )
958 {
959 matrix().compress();
960 }
961 }
962
964 void clear()
965 {
966 matrix().clear();
967 // clean matrix adapter and other helper classes
968 removeObj();
969 }
970
971 void unitRow( const size_t row )
972 {
973 matrix().unitRow( row );
974 }
975
976 protected:
977 template <class Container> // could be std::set or std::vector
978 void setUnitRowImpl( const Container &rows, const double diagonal )
979 {
980 for (const auto& r : rows)
981 {
982 const std::size_t blockRow( r/(LittleBlockType :: rows) );
983 const std::size_t localRowIdx( r%(LittleBlockType :: rows) );
984
985 auto row = matrix().slicedRowIt( blockRow );
986 assert( row != matrix().end() );
987 const auto endcol = (*row).end();
988#ifndef NDEBUG
989 bool set = false;
990#endif
991 for (auto col=(*row).begin(); col!=endcol; ++col)
992 {
993 for (auto& entry : (*col)[localRowIdx])
994 entry = 0;
995 if (col.index() == blockRow)
996 {
997 (*col)[localRowIdx][localRowIdx] = diagonal;
998#ifndef NDEBUG
999 set = true;
1000#endif
1001 }
1002 }
1003 assert(set);
1004 }
1005 }
1006
1007 public:
1008 template <class Container>
1009 void setUnitRows( const Container& unitRows, const Container& auxRows )
1010 {
1011 setUnitRowImpl( unitRows, 1.0 );
1012 setUnitRowImpl( auxRows, 0.0 );
1013 }
1014
1016 void reserve()
1017 {
1018 reserve( Stencil<DomainSpaceType,RangeSpaceType>(domainSpace_, rangeSpace_), false );
1019 }
1020
1022 template <class Set>
1023 void reserve (const std::vector< Set >& sparsityPattern )
1024 {
1025 reserve( StencilWrapper< DomainSpaceType,RangeSpaceType, Set >( sparsityPattern ), false );
1026 }
1027
1029 template <class Stencil>
1030 void reserve(const Stencil &stencil, const bool proposeImplicit = false )
1031 {
1032 // if grid sequence number changed, rebuild matrix
1033 if(sequence_ != domainSpace().sequence())
1034 {
1035 removeObj();
1036
1037 // do not use implicit build mode when multi threading is enabled
1038 const bool implicit =
1039#ifdef USE_IBCRS_MATRIX
1040 false;
1041#else
1042 proposeImplicit && MPIManager::numThreads() == 1;
1043#endif
1044
1045 if( implicit )
1046 {
1047 auto nnz = stencil.maxNonZerosEstimate();
1048 if( nnz == 0 )
1049 {
1050 if (domainSpace_.begin() != domainSpace_.end() && rangeSpace_.begin() != rangeSpace_.end())
1051 {
1052 Stencil tmpStencil( stencil );
1053 tmpStencil.fill( *(domainSpace_.begin()), *(rangeSpace_.begin()) );
1054 nnz = tmpStencil.maxNonZerosEstimate();
1055 }
1056 }
1057 matrix_.reset( new MatrixType( rowMapper_.size(), colMapper_.size(), nnz, overflowFraction_ ) );
1058 }
1059 else
1060 {
1061 matrix_.reset( new MatrixType( rowMapper_.size(), colMapper_.size() ) );
1062 matrix().createEntries( stencil.globalStencil() );
1063 }
1064
1065 sequence_ = domainSpace().sequence();
1066 }
1067 }
1068
1070 template <class HangingNodesType>
1071 void changeHangingNodes(const HangingNodesType& hangingNodes)
1072 {
1073 // create new matrix
1074 MatrixType* newMatrix = new MatrixType(rowMapper_.size(), colMapper_.size());
1075
1076 // setup with hanging rows
1077 newMatrix->setup( *matrix_ , hangingNodes );
1078
1079 // remove old matrix
1080 removeObj();
1081
1082 // store new matrix
1083 matrix_.reset( newMatrix );
1084 }
1085
1088 void extractDiagonal( ColumnDiscreteFunctionType& diag ) const
1089 {
1090 // extract diagonal entries
1091 matrix().extractDiagonal( diag.blockVector() );
1092 }
1093
1095 bool rightPrecondition() const
1096 {
1097 return false;
1098 }
1099
1101 void apply(const ColumnDiscreteFunctionType& arg, RowDiscreteFunctionType& dest) const
1102 {
1103 matrixAdapter().apply( arg.blockVector(), dest.blockVector() );
1104 }
1105
1107 template <class CDF, class RDF>
1108 void apply(const CDF& arg, RDF& dest) const
1109 {
1110 if( ! istlArg_ )
1111 {
1112 istlArg_.reset( new ColumnDiscreteFunctionType( "ISTLMatrixObj::istlArg_", domainSpace() ) );
1113 }
1114
1115 if( ! istlDest_ )
1116 {
1117 istlDest_.reset( new RowDiscreteFunctionType( "ISTLMatrixObj::istlDest_", rangeSpace() ) );
1118 }
1119
1120 istlArg_->assign( arg );
1121 apply( *istlArg_, *istlDest_ );
1122 dest.assign( *istlDest_ );
1123 }
1124
1126 void resort()
1127 {}
1128
1131 void createPreconditionMatrix()
1132 {}
1133
1135 void print(std::ostream & s) const
1136 {
1137 matrix().print(s);
1138 }
1139
1140 const DomainSpaceType& domainSpace() const
1141 {
1142 return domainSpace_;
1143 }
1144 const RangeSpaceType& rangeSpace() const
1145 {
1146 return rangeSpace_;
1147 }
1148
1149 const RowMapperType& rowMapper() const
1150 {
1151 return rowMapper_;
1152 }
1153 const ColMapperType& colMapper() const
1154 {
1155 return colMapper_;
1156 }
1157
1159 ObjectType* newObject() const
1160 {
1161 return new ObjectType(*this, domainSpace(), rangeSpace());
1162 }
1163
1168 [[deprecated("Use TemporaryLocalMatrix,LocalContribution and {get,add,set}LocalMatrix")]]
1169 LocalMatrixType localMatrix( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity ) const
1170 {
1171 return LocalMatrixType( localMatrixStack_, domainEntity, rangeEntity );
1172 }
1173
1178 [[deprecated("Use TemporaryLocalMatrix,LocalContribution and {get,add,set}LocalMatrix")]]
1179 LocalMatrixType localMatrix() const
1180 {
1181 return LocalMatrixType( localMatrixStack_ );
1182 }
1183
1184 LocalColumnObjectType localColumn( const DomainEntityType &domainEntity ) const
1185 {
1186 return LocalColumnObjectType ( *this, domainEntity );
1187 }
1188
1189 protected:
1190 template< class LocalBlock, class Operation >
1191 void applyToBlock ( const size_t row, const size_t col,
1192 const LocalBlock &localBlock,
1193 Operation& operation )
1194 {
1195 LittleBlockType& block = ( implicitModeActive() ) ? matrix().entry( row, col ) : matrix()[ row ][ col ];
1196 for( int i = 0; i < littleRows; ++i )
1197 for( int j = 0; j < littleCols; ++j )
1198 operation( block[ i ][ j ], localBlock[ i ][ j ] );
1199 }
1200
1201 template< class LocalBlock >
1202 void setBlock ( const size_t row, const size_t col,
1203 const LocalBlock &localBlock )
1204 {
1205 typedef typename DomainSpaceType :: RangeFieldType Field;
1206 auto copy = [] ( Field& a, const typename LocalBlock::field_type& b ) { a = b; };
1207 applyToBlock( row, col, localBlock, copy );
1208 }
1209
1210 template< class LocalBlock >
1211 void addBlock ( const size_t row, const size_t col,
1212 const LocalBlock &localBlock )
1213 {
1214 typedef typename DomainSpaceType :: RangeFieldType Field;
1215 auto add = [] ( Field& a, const typename LocalBlock::field_type& b ) { a += b; };
1216 applyToBlock( row, col, localBlock, add );
1217 }
1218
1219 public:
1220 template< class LocalMatrix, class Operation >
1221 void applyToLocalMatrix ( const DomainEntityType &domainEntity,
1222 const RangeEntityType &rangeEntity,
1223 const LocalMatrix &localMat,
1224 Operation& operation )
1225 {
1226 typedef typename MatrixType::size_type Index;
1227#ifndef USE_IBCRS_MATRIX
1228 if( implicitModeActive() )
1229 {
1230 auto blockAccess = [ this ] ( const std::pair< Index, Index > &index ) -> LittleBlockType&
1231 {
1232 return matrix().entry( index.first, index.second );
1233 };
1234 auto functor = [ &localMat, blockAccess, operation ] ( std::pair< int, int > local, const std::pair< Index, Index > &index )
1235 {
1236 LittleBlockType& block = blockAccess( index );
1237 for( int i = 0; i < littleRows; ++i )
1238 for( int j = 0; j < littleCols; ++j )
1239 operation( block[ i ][ j ], localMat.get( local.first * littleRows + i, local.second *littleCols + j ) );
1240 };
1241 rowMapper_.mapEach( rangeEntity, makePairFunctor( colMapper_, domainEntity, functor ) );
1242 }
1243 else
1244#endif
1245 {
1246 auto blockAccess = [ this ] ( const std::pair< Index, Index > &index ) -> LittleBlockType&
1247 {
1248 return matrix()[ index.first][ index.second ];
1249 };
1250 auto functor = [ &localMat, blockAccess, operation ] ( std::pair< int, int > local, const std::pair< Index, Index > &index )
1251 {
1252 LittleBlockType& block = blockAccess( index );
1253 for( int i = 0; i < littleRows; ++i )
1254 for( int j = 0; j < littleCols; ++j )
1255 operation( block[ i ][ j ], localMat.get( local.first * littleRows + i, local.second *littleCols + j ) );
1256 };
1257 rowMapper_.mapEach( rangeEntity, makePairFunctor( colMapper_, domainEntity, functor ) );
1258 }
1259 }
1260
1261 template< class LocalMatrix >
1262 void setLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const LocalMatrix &localMat )
1263 {
1264 typedef typename DomainSpaceType :: RangeFieldType RangeFieldType;
1265 auto operation = [] ( RangeFieldType& a, const RangeFieldType& b )
1266 {
1267 a = b;
1268 };
1269 applyToLocalMatrix( domainEntity, rangeEntity, localMat, operation );
1270 }
1271
1272 template< class LocalMatrix >
1273 void addLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const LocalMatrix &localMat )
1274 {
1275 typedef typename DomainSpaceType :: RangeFieldType RangeFieldType;
1276 auto operation = [] ( RangeFieldType& a, const RangeFieldType& b )
1277 {
1278 a += b;
1279 };
1280 applyToLocalMatrix( domainEntity, rangeEntity, localMat, operation );
1281 }
1282
1283 template< class LocalMatrix, class Scalar >
1284 void addScaledLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const LocalMatrix &localMat, const Scalar &s )
1285 {
1286 typedef typename DomainSpaceType :: RangeFieldType RangeFieldType;
1287 auto operation = [ &s ] ( RangeFieldType& a, const RangeFieldType& b )
1288 {
1289 a += s * b;
1290 };
1291 applyToLocalMatrix( domainEntity, rangeEntity, localMat, operation );
1292 }
1293
1294 template< class LocalMatrix >
1295 void getLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, LocalMatrix &localMat ) const
1296 {
1297 // make sure that matrix is in compressed state if build mode is implicit
1298 finalizeAssembly();
1299
1300 typedef typename MatrixType::size_type Index;
1301 auto functor = [ &localMat, this ] ( std::pair< int, int > local, const std::pair< Index, Index > &global )
1302 {
1303 for( std::size_t i = 0; i < littleRows; ++i )
1304 for( std::size_t j = 0; j < littleCols; ++j )
1305 localMat.set( local.first * littleRows + i, local.second *littleCols + j,
1306 matrix()[ global.first ][ global.second ][i][j] );
1307 };
1308
1309 rowMapper_.mapEach( rangeEntity, makePairFunctor( colMapper_, domainEntity, functor ) );
1310 }
1311
1312 protected:
1313 void preConErrorMsg(int preCon) const
1314 {
1315 exit(1);
1316 }
1317
1318 void removeObj ()
1319 {
1320 matrixAdap_.reset( nullptr );
1321 }
1322 };
1323
1324 } // namespace Fem
1325
1326} // namespace Dune
1327
1328#endif // #if HAVE_DUNE_ISTL
1329
1330#endif // #ifndef DUNE_FEM_ISTLMATRIXWRAPPER_HH
Col col
BCRSMatrix< FieldMatrix< T, n, m >, A >::size_type size_type
double alpha() const
static type * create(const M &mat, bool verbose, bool reusevector)
OperatorHierarchy::ParallelMatrixHierarchy::ConstIterator matrix
void init(const Matrix *matrix)
void add(const Vertex &vertex)
auto rows(Matrix const &matrix)
auto cols(Matrix const &matrix)
int size() const
iterator end()
void clear()
void insert(const T &v)
iterator begin()
static Type apply(T &t)
static TupleAccessTraits< typenameAtType< N, Tuple >::Type >::NonConstType get(Tuple &t)
static constexpr size_type N()
void mv(const X &x, Y &y) const
std::ptrdiff_t index() const
const FieldVector< K, n > & diagonal() const
Iterator beforeBegin()
Iterator beforeEnd()
virtual void operator()()=0
#define DUNE_THROW(E,...)
void print() const
const GlobalIndex & global() const
LocalIndex & local()
typename Overloads::ScalarType< std::decay_t< V > >::type Scalar
STL namespace.
PairFunctor< Mapper, Entity, Functor > makePairFunctor(const Mapper &mapper, const Entity &entity, Functor functor)
Definition operator/matrix/functor.hh:65
T abort(T... args)
T begin(T... args)
T copy(T... args)
T end(T... args)
T endl(T... args)
T exit(T... args)
T find(T... args)
T make_pair(T... args)
T move(T... args)
T prev(T... args)
T reset(T... args)