dune-fem 2.12-git
Loading...
Searching...
No Matches
petscoperator.hh
Go to the documentation of this file.
1#ifndef DUNE_FEM_PETSCLINEAROPERATOR_HH
2#define DUNE_FEM_PETSCLINEAROPERATOR_HH
3
4#include <cassert>
5#include <cstddef>
6
7#include <iostream>
8#include <memory>
9#include <string>
10#include <type_traits>
11#include <vector>
12
14
31
33
34#if HAVE_PETSC
35
36#include "petscmat.h"
37
38
39namespace Dune
40{
41 namespace Fem
42 {
43
44 struct PetscSolverParameter : public LocalParameter< SolverParameter, PetscSolverParameter >
45 {
46 typedef LocalParameter< SolverParameter, PetscSolverParameter > BaseType;
47
48 public:
49 using BaseType :: parameter ;
50 using BaseType :: keyPrefix ;
51
52 PetscSolverParameter( const ParameterReader &parameter = Parameter::container() )
53 : BaseType( parameter )
54 {}
55
56 PetscSolverParameter( const SolverParameter& sp )
57 : PetscSolverParameter( sp.keyPrefix(), sp.parameter() )
58 {}
59
60 PetscSolverParameter( const std::string &keyPrefix, const ParameterReader &parameter = Parameter::container() )
61 : BaseType( keyPrefix, parameter )
62 {}
63
64 bool isPetscSolverParameter() const { return true; }
65
66 static const int boomeramg = 0;
67 static const int parasails = 1;
68 static const int pilut = 2;
69
70 int hypreMethod() const
71 {
72 const std::string hyprePCNames[] = { "boomer-amg", "parasails", "pilu-t" };
73 int hypreType = 0;
74 if (parameter().exists("petsc.preconditioning.method"))
75 {
76 hypreType = parameter().getEnum( "petsc.preconditioning.hypre.method", hyprePCNames, 0 );
77 std::cout << "WARNING: using deprecated parameter 'petsc.preconditioning.hypre.method' use "
78 << keyPrefix() << "preconditioning.hypre.method instead\n";
79 }
80 else
81 hypreType = parameter().getEnum( keyPrefix()+"hypre.method", hyprePCNames, 0 );
82 return hypreType;
83 }
84
85 int superluMethod() const
86 {
87 const std::string factorizationNames[] = { "petsc", "superlu", "mumps" };
88 int factorType = 0;
89 if (parameter().exists("petsc.preconditioning.lu.method"))
90 {
91 factorType = parameter().getEnum( "petsc.preconditioning.lu.method", factorizationNames, 0 );
92 std::cout << "WARNING: using deprecated parameter 'petsc.preconditioning.lu.method' use "
93 << keyPrefix() << "preconditioning.lu.method instead\n";
94 }
95 else
96 factorType = parameter().getEnum( keyPrefix()+"preconditioning.lu.method", factorizationNames, 0 );
97 return factorType;
98 }
99
100 [[deprecated]]
101 bool viennaCL () const {
102 return parameter().getValue< bool > ( keyPrefix() + "petsc.viennacl", false );
103 }
104
105 [[deprecated]]
106 bool blockedMode () const {
107 return parameter().getValue< bool > ( keyPrefix() + "petsc.blockedmode", true );
108 }
109
110 int backend () const
111 {
112 using Dune::Petsc::Backend;
113 return parameter_.getEnum( keyPrefix() + "petsc.backend", Backend::availableBackend(), Backend::defaultBackend );
114 }
115 };
116
117
118
119 /* ========================================
120 * class PetscLinearOperator
121 */
122 template< typename DomainFunction, typename RangeFunction >
123 class PetscLinearOperator
124 : public Fem::AssembledOperator< DomainFunction, RangeFunction >
125 {
126 typedef PetscLinearOperator< DomainFunction, RangeFunction > ThisType;
127 public:
128 typedef Mat MatrixType;
129 typedef DomainFunction DomainFunctionType;
130 typedef RangeFunction RangeFunctionType;
131 typedef typename DomainFunctionType::RangeFieldType DomainFieldType;
132 typedef typename RangeFunctionType::RangeFieldType RangeFieldType;
133 typedef typename DomainFunctionType::DiscreteFunctionSpaceType DomainSpaceType;
134 typedef typename RangeFunctionType::DiscreteFunctionSpaceType RangeSpaceType;
135
136 typedef PetscDiscreteFunction< DomainSpaceType > PetscDomainFunctionType;
137 typedef PetscDiscreteFunction< RangeSpaceType > PetscRangeFunctionType;
138
139 typedef typename DomainSpaceType::EntityType DomainEntityType;
140 typedef typename RangeSpaceType::EntityType RangeEntityType;
141
142 static const unsigned int domainLocalBlockSize = DomainSpaceType::localBlockSize;
143 static const unsigned int rangeLocalBlockSize = RangeSpaceType::localBlockSize;
144
145 static constexpr bool squareBlocked = domainLocalBlockSize == rangeLocalBlockSize ;
146 static constexpr bool blockedMatrix = domainLocalBlockSize > 1 && squareBlocked;
147
148 // is this right? It should be rangeBS x domainBS - the system is
149 // Ad=r so domain gives columns and r gives range
150 typedef FlatFieldMatrix< RangeFieldType, domainLocalBlockSize, rangeLocalBlockSize > MatrixBlockType;
151 typedef MatrixBlockType block_type;
152
153 private:
154 enum Status {statAssembled=0,statAdd=1,statInsert=2,statGet=3,statNothing=4};
155
156 typedef PetscMappers< DomainSpaceType > DomainMappersType;
157 typedef PetscMappers< RangeSpaceType > RangeMappersType;
158
159 typedef AuxiliaryDofs< typename DomainSpaceType::GridPartType, typename DomainMappersType::GhostMapperType > DomainAuxiliaryDofsType;
160 typedef AuxiliaryDofs< typename RangeSpaceType::GridPartType, typename RangeMappersType::GhostMapperType > RangeAuxiliaryDofsType;
161
162 public:
163 // the local matrix
164 class LocalMatrix;
165
166 struct LocalMatrixTraits
167 {
168 typedef typename DomainFunctionType::DiscreteFunctionSpaceType DomainSpaceType;
169 typedef typename RangeFunctionType::DiscreteFunctionSpaceType RangeSpaceType;
170 typedef LocalMatrix LocalMatrixType;
171 typedef typename RangeSpaceType::RangeFieldType RangeFieldType;
172
173 // copied this typedef from spmatrix.hh
174 typedef RangeFieldType LittleBlockType;
175 };
176
178 typedef LocalMatrix ObjectType;
179 typedef ThisType LocalMatrixFactoryType;
180 typedef ObjectStack< LocalMatrixFactoryType > LocalMatrixStackType;
181
183 typedef LocalMatrixWrapper< LocalMatrixStackType > LocalMatrixType;
184 typedef ColumnObject< ThisType > LocalColumnObjectType;
185
186 PetscLinearOperator ( const DomainSpaceType &domainSpace, const RangeSpaceType &rangeSpace,
187 const PetscSolverParameter& param = PetscSolverParameter() )
188 : domainMappers_( domainSpace ),
189 rangeMappers_( rangeSpace ),
190 localMatrixStack_( *this ),
191 status_(statNothing),
192 backend_( param.backend() )
193 {}
194
195 PetscLinearOperator ( const std::string &, const DomainSpaceType &domainSpace, const RangeSpaceType &rangeSpace,
196 const PetscSolverParameter& param = PetscSolverParameter() )
197 : PetscLinearOperator( domainSpace, rangeSpace, param )
198 {}
199
201 ~PetscLinearOperator ()
202 {
203 destroy();
204 }
205
206 void flushAssembly()
207 {
208 ::Dune::Petsc::MatAssemblyBegin( petscMatrix_, MAT_FLUSH_ASSEMBLY );
209 ::Dune::Petsc::MatAssemblyEnd ( petscMatrix_, MAT_FLUSH_ASSEMBLY );
210 // set variable directly since setStatus might be disabled
211 status_ = statAssembled;
212 }
213
214 void finalize ()
215 {
216 if( ! finalizedAlready() )
217 {
218 ::Dune::Petsc::MatAssemblyBegin( petscMatrix_, MAT_FINAL_ASSEMBLY );
219 ::Dune::Petsc::MatAssemblyEnd ( petscMatrix_, MAT_FINAL_ASSEMBLY );
220
221 setUnitRowsImpl( unitRows_, auxRows_ );
222 // remove all cached unit rows
223 unitRows_.clear();
224 auxRows_.clear();
225 }
226 }
227
228 protected:
229 bool finalizedAlready() const
230 {
231 PetscBool assembled = PETSC_FALSE ;
232 ::Dune::Petsc::MatAssembled( petscMatrix_, &assembled );
233 return assembled == PETSC_TRUE;
234 }
235
236 void finalizeAssembly () const
237 {
238 const_cast< ThisType& > (*this).finalize();
239 }
240
241 public:
242 const DomainSpaceType &domainSpace () const { return domainMappers_.space(); }
243 const RangeSpaceType &rangeSpace () const { return rangeMappers_.space(); }
244
248 template <class DF, class RF>
249 void apply ( const DF &arg, RF &dest ) const
250 {
251 if( ! petscArg_ )
252 petscArg_.reset( new PetscDomainFunctionType( "PetscOp-arg", domainSpace(), backend() ) );
253 if( ! petscDest_ )
254 petscDest_.reset( new PetscRangeFunctionType( "PetscOp-dest", rangeSpace(), backend() ) );
255
256 petscArg_->assign( arg );
257 apply( *petscArg_, *petscDest_ );
258 dest.assign( *petscDest_ );
259 }
260
262 void apply ( const PetscDomainFunctionType &arg, PetscRangeFunctionType &dest ) const
263 {
264 // make sure matrix is in correct state
265 finalizeAssembly();
266 ::Dune::Petsc::MatMult( petscMatrix_, *arg.petscVec() , *dest.petscVec() );
267 }
268
269 void operator() ( const DomainFunctionType &arg, RangeFunctionType &dest ) const
270 {
271 apply( arg, dest );
272 }
273
274 void reserve ()
275 {
276 reserve( SimpleStencil<DomainSpaceType,RangeSpaceType>(0), true );
277 }
278
279 template <class Set>
280 void reserve (const std::vector< Set >& sparsityPattern )
281 {
282 reserve( StencilWrapper< DomainSpaceType,RangeSpaceType, Set >( sparsityPattern ), true );
283 }
284
286 template <class StencilType>
287 void reserve (const StencilType &stencil, const bool isSimpleStencil = false )
288 {
289 domainMappers_.update();
290 rangeMappers_.update();
291
292 if(sequence_ != domainSpace().sequence())
293 {
294 // clear Petsc Mat
295 destroy();
296
297 // reset temporary Petsc discrete functions
298 petscArg_.reset();
299 petscDest_.reset();
300
301 // create matrix
302 ::Dune::Petsc::MatCreate( domainSpace().gridPart().comm(), &petscMatrix_ );
303
304 // set sizes of the matrix (columns == domain and rows == range)
305 const PetscInt localCols = domainMappers_.ghostMapper().interiorSize() * domainLocalBlockSize;
306 const PetscInt localRows = rangeMappers_.ghostMapper().interiorSize() * rangeLocalBlockSize;
307
308 const PetscInt globalCols = domainMappers_.parallelMapper().size() * domainLocalBlockSize;
309 const PetscInt globalRows = rangeMappers_.parallelMapper().size() * rangeLocalBlockSize;
310
311 ::Dune::Petsc::MatSetSizes( petscMatrix_, localRows, localCols, globalRows, globalCols );
312
313 PetscInt bs = 1;
314 ::Dune::Petsc::MatSetType( petscMatrix_, ::Dune::Petsc::Backend::toMatType( backend_ ) );
315 if( blockedMode() )
316 {
317 bs = domainLocalBlockSize ;
318 // set block size
319 ::Dune::Petsc::MatSetBlockSize( petscMatrix_, bs );
320 }
321
322 /*
323 std::cout << "Matrix dimension with bs=" << bs << " "
324 << localRows << "x" << localCols << " "
325 << globalRows << "x" << globalCols << " "
326 << rangeLocalBlockSize/bs << "x" << domainLocalBlockSize/bs << " "
327 << std::endl;
328 */
329
330 // there is an issue with the stencil and non zero pattern in the
331 // case of domainSpace != rangeSpace. In this case additional
332 // mallocs are required during matrix assembly which heavily
333 // impacts the preformance. As a quick fix we use a global value
334 // for the number of non zeros per row. That leads to a
335 // significant increase in memory usage but not to much
336 // computational overhead in assembly. The issue with the stencil
337 // is a bug and needs fixing....
338 if( isSimpleStencil || std::is_same< StencilType,SimpleStencil<DomainSpaceType,RangeSpaceType> >::value )
339 {
340 ::Dune::Petsc::MatSetUp( petscMatrix_, bs, domainLocalBlockSize * stencil.maxNonZerosEstimate() );
341 }
342 else
343 {
344 DomainAuxiliaryDofsType domainAuxiliaryDofs( domainMappers_.ghostMapper() );
345 RangeAuxiliaryDofsType rangeAuxiliaryDofs( rangeMappers_.ghostMapper() );
346
347 std::vector< PetscInt > d_nnz( localRows / bs, 0 );
348 std::vector< PetscInt > o_nnz( localRows / bs, 0 );
349 for( const auto& entry : stencil.globalStencil() )
350 {
351 const int petscIndex = rangeMappers_.ghostIndex( entry.first );
352 if( rangeAuxiliaryDofs.contains( petscIndex ) )
353 continue;
354
355 for (unsigned int rb = 0; rb<rangeLocalBlockSize/bs; ++rb)
356 {
357 const size_t row = petscIndex*rangeLocalBlockSize/bs + rb;
358 // Remark: ghost entities should not be inserted into the stencil for dg to
359 // get optimal results but they are needed for istl....
360 assert( row < size_t(localRows/bs) );
361 d_nnz[ row ] = o_nnz[ row ] = 0;
362 for( const auto local : entry.second )
363 {
364 if( !domainAuxiliaryDofs.contains( domainMappers_.ghostIndex( local ) ) )
365 d_nnz[ row ] += domainLocalBlockSize/bs;
366 else
367 o_nnz[ row ] += domainLocalBlockSize/bs;
368 }
369 }
370 }
371 ::Dune::Petsc::MatSetUp( petscMatrix_, bs, &d_nnz[0], &o_nnz[0] );
372 }
373 sequence_ = domainSpace().sequence();
374 }
375
376 flushAssembly();
377 status_ = statAssembled ;
378 }
379
380 virtual void clear ()
381 {
382 flushAssembly();
383 ::Dune::Petsc::MatZeroEntries( petscMatrix_ );
384 flushAssembly();
385
386 unitRows_.clear();
387 auxRows_.clear();
388 }
389
390 void setUnitRowsImpl( const std::vector< PetscInt >& r,
391 const std::vector< PetscInt >& a )
392 {
393 ::Dune::Petsc::MatZeroRows( petscMatrix_, r.size(), r.data(), 1.0 );
394 ::Dune::Petsc::MatZeroRows( petscMatrix_, a.size(), a.data(), 0.0 );
395 }
396
397 template <class Container> // could bet std::set or std::vector
398 void setUnitRows( const Container& unitRows, const Container& auxRows )
399 {
401 r.reserve( unitRows.size() );
402 a.reserve( auxRows.size() );
403
404 auto setupRows = [this] (const Container& rows, std::vector< PetscInt >& r )
405 {
406 for( const auto& row : rows )
407 {
408 const PetscInt block = this->rangeMappers_.parallelIndex( row / rangeLocalBlockSize );
409 r.push_back( block * rangeLocalBlockSize + (row % rangeLocalBlockSize) );
410 }
411 };
412
413 setupRows( unitRows, r );
414 setupRows( auxRows, a );
415
416 if( finalizedAlready() )
417 {
418 setUnitRowsImpl( r, a );
419 }
420 else
421 {
422 unitRows_.reserve( unitRows_.size() + r.size() );
423 for( const auto& row : r )
424 unitRows_.push_back( row );
425
426 auxRows_.reserve( auxRows_.size() + a.size() );
427 for( const auto& row : a )
428 auxRows_.push_back( row );
429 }
430 }
431
433 ObjectType* newObject() const
434 {
435 return new ObjectType( *this, domainSpace(), rangeSpace() );
436 }
437
442 [[deprecated("Use TemporaryLocalMatrix,LocalContribution and {get,add,set}LocalMatrix")]]
443 LocalMatrixType localMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity ) const
444 {
445 return LocalMatrixType(localMatrixStack_, domainEntity, rangeEntity);
446 }
447
448 LocalColumnObjectType localColumn( const DomainEntityType &colEntity ) const
449 {
450 return LocalColumnObjectType ( *this, colEntity );
451 }
452
453 public:
454 void unitRow( const PetscInt localRow, const PetscScalar diag = 1.0 )
455 {
457 const PetscInt row = rangeMappers_.parallelIndex( localRow );
458 for( unsigned int i=0, r = row * domainLocalBlockSize; i<domainLocalBlockSize; ++i, ++r )
459 {
460 rows[ i ] = r;
461 }
462
463 if( finalizedAlready() )
464 {
465 // set given row to a zero row with diagonal entry equal to diag
466 ::Dune::Petsc::MatZeroRows( petscMatrix_, domainLocalBlockSize, rows.data(), diag );
467 }
468 else
469 {
470 // this only works for diag = 1
471 assert( std::abs( diag - 1. ) < 1e-12 );
472 unitRows_.reserve( unitRows_.size() + domainLocalBlockSize );
473 for( const auto& r : rows )
474 {
475 unitRows_.push_back( r );
476 }
477 }
478 }
479
480 bool blockedMode() const { return backend() == Dune::Petsc::Backend::block; }
481
483 const int backend () const { return backend_; }
484
485 protected:
486 template< class PetscOp >
487 void applyToBlock ( const PetscInt localRow, const PetscInt localCol, const MatrixBlockType& block, PetscOp op )
488 {
489#ifndef NDEBUG
490 const PetscInt localCols = domainMappers_.ghostMapper().interiorSize() * domainLocalBlockSize;
491 const PetscInt localRows = rangeMappers_.ghostMapper().interiorSize() * rangeLocalBlockSize;
492 assert( localRow < localRows );
493 assert( localCol < localCols );
494#endif
495
496 if( blockedMode() )
497 {
498 // convert process local indices to global indices
499 const PetscInt row = rangeMappers_.parallelIndex( localRow );
500 const PetscInt col = rangeMappers_.parallelIndex( localCol );
501 ::Dune::Petsc::MatSetValuesBlocked( petscMatrix_, 1, &row, 1, &col, block.data(), op );
502 }
503 else
504 {
505 // convert process local indices to global indices
506 const PetscInt row = rangeMappers_.parallelIndex( localRow );
507 const PetscInt col = rangeMappers_.parallelIndex( localCol );
510 for( unsigned int i=0, r = row * domainLocalBlockSize, c = col * domainLocalBlockSize; i<domainLocalBlockSize; ++i, ++r, ++c )
511 {
512 rows[ i ] = r;
513 cols[ i ] = c;
514 }
515
516 // set given row to a zero row with diagonal entry equal to diag
517 ::Dune::Petsc::MatSetValues( petscMatrix_, domainLocalBlockSize, rows.data(), domainLocalBlockSize, cols.data(), block.data(), op );
518 }
519 setStatus( statAssembled );
520 }
521
522 template< class LocalBlock, class PetscOp >
523 void applyToBlock ( const size_t row, const size_t col, const LocalBlock& block, PetscOp op )
524 {
525 assert( block.rows() == rangeLocalBlockSize );
526 assert( block.cols() == domainLocalBlockSize );
527
528 // copy to MatrixBlockType data structure suited to be inserted into Mat
529 MatrixBlockType matBlock( block );
530 applyToBlock( row, col, matBlock, op );
531 }
532
533 template< class LocalBlock >
534 void setBlock ( const size_t row, const size_t col, const LocalBlock& block )
535 {
536#ifndef USE_SMP_PARALLEL
537 assert( status_==statAssembled || status_==statInsert );
538#endif
539 assert( row < std::numeric_limits< int > :: max() );
540 assert( col < std::numeric_limits< int > :: max() );
541
542 setStatus( statInsert );
543 applyToBlock( static_cast< PetscInt > (row), static_cast< PetscInt > (col), block, INSERT_VALUES );
544 }
545
546 template< class LocalBlock >
547 void addBlock ( const size_t row, const size_t col, const LocalBlock& block )
548 {
549#ifndef USE_SMP_PARALLEL
550 assert( status_==statAssembled || status_==statInsert );
551#endif
552 assert( row < std::numeric_limits< int > :: max() );
553 assert( col < std::numeric_limits< int > :: max() );
554
555 setStatus( statAdd );
556 applyToBlock( static_cast< PetscInt > (row), static_cast< PetscInt > (col), block, ADD_VALUES );
557 }
558
559 protected:
560 typedef TemporaryLocalMatrix< DomainSpaceType, RangeSpaceType > TemporaryLocalMatrixType;
561
562 // specialization for temporary local matrix, then copy of values is not needed
563 template <class Operation>
564 const PetscScalar* getValues( const unsigned int rSize, const unsigned int cSize,
565 const TemporaryLocalMatrixType &localMat, const Operation&,
567 {
568 return localMat.data();
569 }
570
571 // specialization for temporary local matrix, then copy of values is not needed
572 template <class LM, class Operation>
573 const PetscScalar* getValues( const unsigned int rSize, const unsigned int cSize,
574 const Assembly::Impl::LocalMatrixGetter< LM >& localMat, const Operation&,
576 {
577 return localMat.localMatrix().data();
578 }
579
580 // retrieve values for arbitrary local matrix
581 template <class LocalMatrix, class Operation, bool T>
582 const PetscScalar* getValues( const unsigned int rSize, const unsigned int cSize,
583 const LocalMatrix &localMat, const Operation& operation,
585 {
587 v.resize( rSize * cSize );
588 for( unsigned int i = 0, ic = 0 ; i< rSize; ++i )
589 {
590 for( unsigned int j =0; j< cSize; ++j, ++ic )
591 {
592 v[ ic ] = operation( localMat.get( i, j ) );
593 }
594 }
595 return v.data();
596 }
597
598 template< class LocalMatrix, class Operation, class PetscOp, bool T >
599 void applyLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity,
600 const LocalMatrix &localMat, const Operation& operation,
601 PetscOp petscOp,
603 {
604 auto& rcTemp = *(rcTemp_);
605 std::vector< PetscInt >& r = rcTemp.first;
606 std::vector< PetscInt >& c = rcTemp.second;
607
608 if( blockedMode() )
609 {
610 setupIndicesBlocked( rangeMappers_, rangeEntity, r );
611 setupIndicesBlocked( domainMappers_, domainEntity, c );
612
613 // domainLocalBlockSize == rangeLocalBlockSize
614 const unsigned int rSize = r.size() * domainLocalBlockSize ;
615 const unsigned int cSize = c.size() * domainLocalBlockSize ;
616
617 const PetscScalar* values = getValues( rSize, cSize, localMat, operation, scaled );
618 ::Dune::Petsc::MatSetValuesBlocked( petscMatrix_, r.size(), r.data(), c.size(), c.data(), values, petscOp );
619 }
620 else
621 {
622 setupIndices( rangeMappers_, rangeEntity, r );
623 setupIndices( domainMappers_, domainEntity, c );
624
625 const unsigned int rSize = r.size();
626 const unsigned int cSize = c.size();
627
628 const PetscScalar* values = getValues( rSize, cSize, localMat, operation, scaled );
629 ::Dune::Petsc::MatSetValues( petscMatrix_, rSize, r.data(), cSize, c.data(), values, petscOp );
630 }
631 setStatus( statAssembled );
632 }
633
634 public:
635 template< class LocalMatrix >
636 void addLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const LocalMatrix &localMat )
637 {
638#ifndef USE_SMP_PARALLEL
639 assert( status_==statAssembled || status_==statAdd );
640#endif
641 setStatus( statAdd );
642
643 auto operation = [] ( const PetscScalar& value ) -> PetscScalar { return value; };
644
645 applyLocalMatrix( domainEntity, rangeEntity, localMat, operation, ADD_VALUES, std::integral_constant< bool, false>() );
646 }
647
648 template< class LocalMatrix, class Scalar >
649 void addScaledLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const LocalMatrix &localMat, const Scalar &s )
650 {
651#ifndef USE_SMP_PARALLEL
652 assert( status_==statAssembled || status_==statAdd );
653#endif
654 setStatus( statAdd );
655
656 auto operation = [ &s ] ( const PetscScalar& value ) -> PetscScalar { return s * value; };
657
658 applyLocalMatrix( domainEntity, rangeEntity, localMat, operation, ADD_VALUES, std::integral_constant< bool, true>() );
659 }
660
661 template< class LocalMatrix >
662 void setLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const LocalMatrix &localMat )
663 {
664#ifndef USE_SMP_PARALLEL
665 assert( status_==statAssembled || status_==statInsert );
666#endif
667 setStatus( statInsert );
668
669 auto operation = [] ( const PetscScalar& value ) -> PetscScalar { return value; };
670
671 applyLocalMatrix( domainEntity, rangeEntity, localMat, operation, INSERT_VALUES, std::integral_constant< bool, false>() );
672 }
673
674 template< class LocalMatrix >
675 void getLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, LocalMatrix &localMat ) const
676 {
677 // make sure matrix is in correct state before using
678 finalizeAssembly();
679
680#ifndef USE_SMP_PARALLEL
681 assert( status_==statAssembled || status_==statGet );
682#endif
683 setStatus( statGet );
684
685 auto& rcTemp = *(rcTemp_);
686 std::vector< PetscInt >& r = rcTemp.first;
687 std::vector< PetscInt >& c = rcTemp.second;
689
690 setupIndices( rangeMappers_, rangeEntity, r );
691 setupIndices( domainMappers_, domainEntity, c );
692
693 v.resize( r.size() * c.size() );
694 ::Dune::Petsc::MatGetValues( petscMatrix_, r.size(), r.data(), c.size(), c.data(), v.data() );
695
696 for( std::size_t i =0 ; i< r.size(); ++i )
697 for( std::size_t j =0; j< c.size(); ++j )
698 localMat.set( i, j, v[ i * c.size() +j ] );
699
700 setStatus( statAssembled );
701 }
702
703 void scaleLocalMatrix ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity, const RangeFieldType &s )
704 {
705 // make sure matrix is in correct state before using
706 finalizeAssembly();
707
708#ifndef USE_SMP_PARALLEL
709 assert( status_==statAssembled || status_==statGet );
710#endif
711 setStatus( statGet );
712
713 auto& rcTemp = *(rcTemp_);
714 std::vector< PetscInt >& r = rcTemp.first;
715 std::vector< PetscInt >& c = rcTemp.second;
717
718 setupIndices( rangeMappers_, rangeEntity, r );
719 setupIndices( domainMappers_, domainEntity, c );
720
721 const unsigned int rSize = r.size();
722 const unsigned int cSize = c.size();
723 const std::size_t size = rSize * cSize;
724
725 v.resize( size );
726 // get values
727 ::Dune::Petsc::MatGetValues( petscMatrix_, r.size(), r.data(), c.size(), c.data(), v.data() );
728
729 // scale values
730 for( std::size_t i=0; i<size; ++i )
731 v[ i ] *= s;
732
733 // set values again
734 ::Dune::Petsc::MatSetValues( petscMatrix_, rSize, r.data(), cSize, c.data(), v.data(), INSERT_VALUES );
735 setStatus( statAssembled );
736 }
737
738 // just here for debugging
739 void view () const
740 {
741 ::Dune::Petsc::MatView( petscMatrix_, PETSC_VIEWER_STDOUT_WORLD );
742 }
743
744 // print matrix just here for debugging
745 void print( std::ostream& s ) const
746 {
747 if( &s == &std::cout || &s == &std::cerr )
748 {
749 view();
750 }
751 }
752
753 // return reference to PETSc matrix object
754 Mat& exportMatrix () const
755 {
756 // make sure matrix is in correct state
757 finalizeAssembly();
758 return petscMatrix_;
759 }
760
761 private:
762 PetscLinearOperator ();
763
765 void destroy ()
766 {
767 if( status_ != statNothing )
768 {
769 ::Dune::Petsc::MatDestroy( &petscMatrix_ );
770 status_ = statNothing ;
771 }
772 sequence_ = -1;
773 unitRows_.clear();
774 auxRows_.clear();
775 }
776
777 void setStatus (const Status &newstatus) const
778 {
779 // in case OpenMP is used simply avoid status check
780#ifndef USE_SMP_PARALLEL
781 status_ = newstatus;
782#endif
783 }
784
785 template< class DFS, class Entity >
786 static void setupIndices ( const PetscMappers< DFS > &mappers, const Entity &entity, std::vector< PetscInt > &indices )
787 {
788 NonBlockMapper< const typename PetscMappers< DFS >::ParallelMapperType, DFS::localBlockSize > nonBlockMapper( mappers.parallelMapper() );
789 nonBlockMapper.map( entity, indices );
790 }
791
792 template< class DFS, class Entity >
793 static void setupIndicesBlocked ( const PetscMappers< DFS > &mappers, const Entity &entity, std::vector< PetscInt > &indices )
794 {
795 mappers.parallelMapper().map( entity, indices );
796 }
797
798 /*
799 * data fields
800 */
801 DomainMappersType domainMappers_;
802 RangeMappersType rangeMappers_;
803
804 int sequence_ = -1;
805 mutable Mat petscMatrix_;
806
807 mutable LocalMatrixStackType localMatrixStack_;
808 mutable Status status_;
809
810 const int backend_;
811
814
815 mutable ThreadSafeValue< std::vector< PetscScalar > > v_;
816 mutable ThreadSafeValue< std::pair< std::vector< PetscInt >, std::vector< PetscInt > > > rcTemp_;
817
818 mutable std::vector< PetscInt > unitRows_;
819 mutable std::vector< PetscInt > auxRows_;
820 };
821
822
823
824 /* ========================================
825 * class PetscLinearOperator::LocalMatrix
826 */
827 template< typename DomainFunction, typename RangeFunction >
828 class PetscLinearOperator< DomainFunction, RangeFunction >::LocalMatrix
829 : public LocalMatrixDefault< typename PetscLinearOperator< DomainFunction, RangeFunction >::LocalMatrixTraits >
830 {
831 typedef LocalMatrix ThisType;
832 typedef LocalMatrixDefault< typename PetscLinearOperator< DomainFunction, RangeFunction >::LocalMatrixTraits > BaseType;
833
834 typedef PetscLinearOperator< DomainFunction, RangeFunction > PetscLinearOperatorType;
835
836
837 public:
838 typedef PetscInt DofIndexType;
839 typedef std::vector< DofIndexType > IndexVectorType;
840 typedef typename DomainFunction::DiscreteFunctionSpaceType DomainSpaceType;
841 typedef typename RangeFunction::DiscreteFunctionSpaceType RangeSpaceType;
842 typedef typename DomainSpaceType::BasisFunctionSetType DomainBasisFunctionSetType;
843 typedef typename RangeSpaceType::BasisFunctionSetType RangeBasisFunctionSetType;
844
845 enum { rangeBlockSize = RangeSpaceType::localBlockSize };
846 enum { domainBlockSize = DomainSpaceType ::localBlockSize };
847
848 private:
849
850 // needed for .mapEach below
851 template< typename PetscMapping >
852 struct PetscAssignFunctor
853 {
854 explicit PetscAssignFunctor ( const PetscMapping &petscMapping, IndexVectorType &indices )
855 : petscMapping_( petscMapping ),
856 indices_( indices )
857 {}
858
859 template< typename T >
860 void operator() ( const std::size_t localIndex, T globalIndex ) { indices_[ localIndex ] = petscMapping_.globalMapping( globalIndex ); }
861
862 private:
863 const PetscMapping &petscMapping_;
864 IndexVectorType &indices_;
865 };
866
867 public:
868 [[deprecated("Use TemporaryLocal Matrix and {add,set,get}LocalMatrix")]]
869 LocalMatrix ( const PetscLinearOperatorType &petscLinOp,
870 const DomainSpaceType &domainSpace,
871 const RangeSpaceType &rangeSpace )
872 : BaseType( domainSpace, rangeSpace ),
873 petscLinearOperator_( petscLinOp )
874 {}
875
876 void finalize()
877 {
878 }
879
880 void init ( const DomainEntityType &domainEntity, const RangeEntityType &rangeEntity )
881 {
882 // call initialize on base class
883 BaseType :: init( domainEntity, rangeEntity );
884
885 //*************************************************
886 // The rows belong to the domain space
887 // it's indices are determained by the rangeSpace
888 //
889 // The columns belong to the range space
890 // it's indices are determained by the domainSpace
891 //*************************************************
892
893 setupIndices( petscLinearOperator_.rangeMappers_, rangeEntity, rowIndices_ );
894 setupIndices( petscLinearOperator_.domainMappers_, domainEntity, colIndices_ );
895
896 status_ = statAssembled;
897 petscLinearOperator_.setStatus(status_);
898 }
899
900 inline void add ( const int localRow, const int localCol, const RangeFieldType &value )
901 {
902 assert( status_==statAssembled || status_==statAdd );
903 status_ = statAdd;
904 petscLinearOperator_.setStatus(status_);
905 ::Dune::Petsc::MatSetValue( petscMatrix(), globalRowIndex( localRow ), globalColIndex( localCol ) , value, ADD_VALUES );
906 }
907
908 inline void set(const int localRow, const int localCol, const RangeFieldType &value )
909 {
910 assert( status_==statAssembled || status_==statInsert );
911 status_ = statInsert;
912 petscLinearOperator_.setStatus(status_);
913 ::Dune::Petsc::MatSetValue( petscMatrix(), globalRowIndex( localRow ), globalColIndex( localCol ) , value, INSERT_VALUES );
914 }
915
917 void clearRow ( const int localRow )
918 {
919 assert( status_==statAssembled || status_==statInsert );
920 status_ = statInsert;
921 petscLinearOperator_.setStatus(status_);
922 const int col = this->columns();
923 const int globalRowIdx = globalRowIndex( localRow );
924 for(int localCol=0; localCol<col; ++localCol)
925 {
926 ::Dune::Petsc::MatSetValue( petscMatrix(), globalRowIdx, globalColIndex( localCol ), 0.0, INSERT_VALUES );
927 }
928 }
929
930 inline const RangeFieldType get ( const int localRow, const int localCol ) const
931 {
932 assert( status_==statAssembled || status_==statGet );
933 status_ = statGet;
934 petscLinearOperator_.setStatus(status_);
935 RangeFieldType v[1];
936 const int r[] = {globalRowIndex( localRow )};
937 const int c[] = {globalColIndex( localCol )};
938 ::Dune::Petsc::MatGetValues( petscMatrix(), 1, r, 1, c, v );
939 return v[0];
940 }
941
942 inline void scale ( const RangeFieldType &factor )
943 {
944 const_cast< PetscLinearOperatorType& > (petscLinearOperator_).scaleLocalMatrix( this->domainEntity(), this->rangeEntity(), factor );
945 }
946
947 private:
948 LocalMatrix ();
949
950 Mat& petscMatrix () { return petscLinearOperator_.petscMatrix_; }
951 const Mat& petscMatrix () const { return petscLinearOperator_.petscMatrix_; }
952
953 public:
954 int rows() const { return rowIndices_.size(); }
955 int columns() const { return colIndices_.size(); }
956
957 private:
958 DofIndexType globalRowIndex( const int localRow ) const
959 {
960 assert( localRow < static_cast< int >( rowIndices_.size() ) );
961 return rowIndices_[ localRow ];
962 }
963
964 DofIndexType globalColIndex( const int localCol ) const
965 {
966 assert( localCol < static_cast< int >( colIndices_.size() ) );
967 return colIndices_[ localCol ];
968 }
969
970 /*
971 * data fields
972 */
973 const PetscLinearOperatorType &petscLinearOperator_;
974 IndexVectorType rowIndices_;
975 IndexVectorType colIndices_;
976 mutable Status status_;
977 };
978
979
980 } // namespace Fem
981
982} // namespace Dune
983
984#endif // #if HAVE_PETSC
985
986#endif // #ifndef DUNE_FEM_PETSCLINEAROPERATOR_HH
Col col
void init(const Matrix *matrix)
void add(const Vertex &vertex)
auto rows(Matrix const &matrix)
auto cols(Matrix const &matrix)
void push_back(const MemberType &item)
int size() const
void clear()
void destroy(pointer p)
static Type apply(T &t)
static TupleAccessTraits< typenameAtType< N, Tuple >::Type >::NonConstType get(Tuple &t)
bool exists(size_type i, size_type j) const
virtual void operator()()=0
void print() const
LocalIndex & local()
typename Overloads::ScalarType< std::decay_t< V > >::type Scalar
const Communication & comm() const
Dune::Fem::Double abs(const Dune::Fem::Double &a)
Definition double.hh:942
GridImp::template Codim< cd >::Entity Entity
T data(T... args)
T push_back(T... args)
T reserve(T... args)
T resize(T... args)
T size(T... args)