dune-fem 2.12-git
Loading...
Searching...
No Matches
petscvector.hh
Go to the documentation of this file.
1#ifndef DUNE_FEM_PETSCVECTOR_HH
2#define DUNE_FEM_PETSCVECTOR_HH
3
4#include <cassert>
5#include <cstddef>
6
7#include <algorithm>
8#include <string>
9
11
14
17
19
20
21#if HAVE_PETSC
22
28
29namespace Dune
30{
31
32 namespace Fem
33 {
34
35 // Internal Forward Declarations
36 // -----------------------------
37
38 template< class DFSpace >
39 class PetscVector;
40
41
42 // External Forward Declarations
43 // -----------------------------
44
45 template< class >
46 class PetscDofBlock;
47
48 template< class >
49 class PetscDofProxy;
50
51
52
53 // PetscManagedDofStorage
54 // ----------------------
55
57 template < class DiscreteFunctionSpace, class Mapper >
58 class PetscManagedDofStorage
59 : public ManagedDofStorageImplementation< typename DiscreteFunctionSpace::GridPartType::GridType, Mapper, PetscVector< DiscreteFunctionSpace > >
60 {
61 typedef typename DiscreteFunctionSpace::GridPartType::GridType GridType;
62 typedef Mapper MapperType ;
63 typedef PetscVector< DiscreteFunctionSpace > DofArrayType ;
64 typedef ManagedDofStorageImplementation< GridType, MapperType, DofArrayType > BaseType;
65
66 public:
67 typedef typename BaseType :: SizeType SizeType;
68
70 PetscManagedDofStorage( const DiscreteFunctionSpace& space,
71 const MapperType& mapper,
72 const int backend )
73 : BaseType( space.grid(), mapper, myArray_ ),
74 myArray_( space, backend )
75 {
76 }
77
78 void resize( const bool ) override
79 { // do nothing here, only in compress
80 }
81
82 void reserve( const SizeType ) override
83 {
84 // do nothing here, only in compress
85 }
86
87 void dofCompress( const bool clearResizedArrays ) override
88 {
89 myArray_.resize();
90 if( clearResizedArrays )
91 {
92 myArray_.clear();
93 }
94 }
95
97 void enableDofCompression() override
98 {
99 std::cerr << "WARNING: PetscVector cannot handle dof compression!" << std::endl;
100 }
101 protected:
102 DofArrayType myArray_;
103 };
104
105
106
107 // PetscVector
108 // -----------
109
110 /*
111 * This encapsules a PETSc Vec with ghosts.
112 * Some conceptual explanations:
113 * The PETSc vector, as modelled by this class, consists of three parts:
114 * 1) the whole PETSc vector, which might be distributed across several MPI processes.
115 * We call this the _global vector_
116 * 2) Each process holds a portion of this global vector, we call this part the
117 * _process vector_.
118 * 3) And there is a representation of the process vector, which also has 'ghost dof blocks'.
119 * We call this represenation the _ghosted vector_.
120 */
121 template< class DFSpace >
122 class PetscVector
123 {
124 typedef PetscVector< DFSpace > ThisType;
125 friend class PetscDofBlock< ThisType >;
126 friend class PetscDofBlock< const ThisType >;
127 friend class PetscDofProxy< ThisType >;
128 friend class PetscDofProxy< const ThisType >;
129
130 public:
131 typedef PetscScalar value_type ;
132 typedef Vec DofContainerType;
133
134 static constexpr int blockSize = DFSpace::localBlockSize;
135 typedef Hybrid::IndexRange< int, blockSize > BlockIndices;
136
137 typedef PetscDofBlock< ThisType > DofBlockType;
138 typedef PetscDofBlock< const ThisType > ConstDofBlockType;
139 typedef typename DofBlockType::DofIterator DofIteratorType;
140 typedef typename ConstDofBlockType::DofIterator ConstDofIteratorType;
141 typedef Envelope< DofBlockType > DofBlockPtrType;
142 typedef Envelope< ConstDofBlockType > ConstDofBlockPtrType;
143 typedef typename DofBlockType::IndexType IndexType;
144
145 typedef DofIteratorType IteratorType;
146 typedef ConstDofIteratorType ConstIteratorType;
147 typedef typename DFSpace::RangeFieldType FieldType;
148 typedef int SizeType;
149
150 typedef PetscMappers< DFSpace > MappersType;
151
152 struct FakeDF
153 {
154 typedef DFSpace DiscreteFunctionSpaceType;
155 };
156
157 // need to pass something that contains a typedef DiscreteFunctionSpaceType
158 typedef typename DFSpace::template CommDataHandle< FakeDF >::OperationType DefaultCommunicationOperationType;
159
160 // note that Vec is a pointer type so no deep copy is made
161 PetscVector ( const DFSpace& space, Vec vec )
162 : mappers_( space ), vec_(vec),
163 backend_( getBackend( vec ) ), // determine backend from given PetscVec
164 owner_(false)
165 {
166 static_assert( DefaultCommunicationOperationType::value == DFCommunicationOperation::copy ||
167 DefaultCommunicationOperationType::value == DFCommunicationOperation::add,
168 "only copy/add are available communication operations for petsc");
169 ::Dune::Petsc::VecGhostGetLocalForm( vec_, &ghostedVec_ );
170 }
171
172 PetscVector ( const DFSpace& space, const int backend = ::Dune::Petsc::Backend::defaultBackend )
173 : mappers_( space ), backend_( backend ), owner_(true)
174 {
175 static_assert( DefaultCommunicationOperationType::value == DFCommunicationOperation::copy ||
176 DefaultCommunicationOperationType::value == DFCommunicationOperation::add,
177 "only copy/add are available communication operations for petsc");
178 // init vector
179 init();
180 }
181
182 // TODO: think about sequence overflows...
183 PetscVector ( const ThisType &other )
184 : mappers_( other.mappers_ ), backend_( other.backend_ ), owner_(true)
185 {
186 // init vector
187 init();
188
189 // copy dofs
190 assign( other );
191 }
192
193 ~PetscVector ()
194 {
195 if (owner_)
196 // destroy vectors
197 removeObj();
198 }
199
200 std::size_t size () const { return mappers().ghostMapper().size(); }
201
202 void resize( const std::size_t newsize = 0 )
203 {
204 // TODO: keep old data stored in current vector
205 // remove old vectors
206 removeObj();
207
208 // initialize new
209 init();
210
211 hasBeenModified ();
212 }
213
214 void reserve( const std::size_t capacity )
215 {
216 resize( capacity );
217 }
218
219 void hasBeenModified () { ++sequence_; }
220
221 void communicate ()
222 {
223 communicateFlag_ = true;
224 }
225
226 // accessors for the underlying PETSc vectors
227 Vec* getVector ()
228 {
229 communicateIfNecessary();
230 return &vec_;
231 }
232
233 const Vec* getVector () const
234 {
235 communicateIfNecessary();
236 return &vec_;
237 }
238
239 // return type of petsc backend (see petsccommon.hh)
240 const int backend() const { return backend_; }
241
242 // accessors for the underlying PETSc vectors
243 Vec& array ()
244 {
245 communicateIfNecessary();
246 return vec_;
247 }
248
249 const Vec& array () const
250 {
251 communicateIfNecessary();
252 return vec_;
253 }
254
255 Vec* getGhostedVector ()
256 {
257 communicateIfNecessary();
258 return &ghostedVec_;
259 }
260
261 const Vec* getGhostedVector () const
262 {
263 communicateIfNecessary();
264 return &ghostedVec_;
265 }
266
267 void beginAssemble()
268 {
269 ::Dune::Petsc::VecAssemblyBegin( vec_ );
270 }
271
272 void endAssemble( const bool communicate )
273 {
274 ::Dune::Petsc::VecAssemblyEnd( vec_ );
275 if( communicate )
276 communicateIfNecessary();
277 }
278
279 // force communication _now_
280 template <class Operation>
281 void communicateNow (const Operation& operation) const
282 {
283 communicateFlag_ = true;
284 ++sequence_;
285 communicateIfNecessary( operation );
286 }
287
288 DofBlockType operator[] ( const IndexType index ) { return DofBlockType( *this,index ); }
289 ConstDofBlockType operator[] ( const IndexType index ) const { return ConstDofBlockType( *this,index ); }
290
291 ConstDofBlockPtrType block ( IndexType index ) const { return blockPtr( index ); }
292 DofBlockPtrType block ( IndexType index ) { return blockPtr( index ); }
293
294 DofBlockPtrType blockPtr ( IndexType index )
295 {
296 assert( static_cast< std::size_t >( index ) < mappers().size() );
297 return DofBlockPtrType( typename DofBlockType::UnaryConstructorParamType( *this, index ) );
298 }
299
300 ConstDofBlockPtrType blockPtr ( IndexType index ) const
301 {
302 assert( static_cast< std::size_t >( index ) < mappers().size() );
303 return ConstDofBlockPtrType( typename ConstDofBlockType::UnaryConstructorParamType( *this, index ) );
304 }
305
306 DofIteratorType begin () { return DofIteratorType( *this, 0, 0 ); }
307 ConstDofIteratorType begin () const { return ConstDofIteratorType( *this, 0, 0 ); }
308 DofIteratorType end () { return DofIteratorType( *this, mappers().size() ); }
309 ConstDofIteratorType end () const { return ConstDofIteratorType( *this, mappers().size() ); }
310
311 DofIteratorType beforeEnd ()
312 {
313 DUNE_THROW(NotImplemented,"PetscVector::beforeEnd is not implemented yet");
314 return end();
315 }
316
317 ConstDofIteratorType beforeEnd () const
318 {
319 DUNE_THROW(NotImplemented,"PetscVector::beforeEnd is not implemented yet");
320 return end();
321 }
322
323 DofIteratorType beforeBegin ()
324 {
325 DUNE_THROW(NotImplemented,"PetscVector::beforeBegin is not implemented yet");
326 return end();
327 }
328 ConstDofIteratorType beforeBegin () const
329 {
330 DUNE_THROW(NotImplemented,"PetscVector::beforeBegin is not implemented yet");
331 return end();
332 }
333
334 DofIteratorType dbegin () { return begin(); }
335 ConstDofIteratorType dbegin () const { return begin(); }
336 DofIteratorType dend () { return end(); }
337 ConstDofIteratorType dend () const { return end(); }
338
339 void clear ()
340 {
341 ::Dune::Petsc::VecSet( *getVector(), 0. );
342 updateGhostRegions();
343 vectorIsUpToDateNow();
344 }
345
346 PetscScalar operator* ( const ThisType &other ) const
347 {
348 PetscScalar ret;
349 ::Dune::Petsc::VecDot( *getVector(), *other.getVector(), &ret );
350 return ret;
351 }
352
353 const ThisType& operator+= ( const ThisType &other )
354 {
355 ::Dune::Petsc::VecAXPY( *getVector(), 1., *other.getVector() );
356 updateGhostRegions();
357 vectorIsUpToDateNow();
358 return *this;
359 }
360
361 const ThisType& operator-= ( const ThisType &other )
362 {
363 ::Dune::Petsc::VecAXPY( *getVector(), -1., *other.getVector() );
364 updateGhostRegions();
365 vectorIsUpToDateNow();
366 return *this;
367 }
368
369 const ThisType& operator*= ( PetscScalar scalar )
370 {
371 ::Dune::Petsc::VecScale( *getVector(), scalar );
372 updateGhostRegions();
373 vectorIsUpToDateNow();
374 return *this;
375 }
376
377 const ThisType& operator/= ( PetscScalar scalar )
378 {
379 assert( scalar != 0 );
380 return this->operator*=( 1./scalar );
381 }
382
383 void axpy ( const PetscScalar &scalar, const ThisType &other )
384 {
385 ::Dune::Petsc::VecAXPY( *getVector(), scalar, *other.getVector() );
386 hasBeenModified();
387 }
388
389 void clearGhost( )
390 {
391 PetscScalar *array;
392 // create local memory
393 VecGetArray( ghostedVec_,&array );
394 std::fill_n( array + mappers().ghostMapper().interiorSize() * blockSize, mappers().ghostMapper().ghostSize() * blockSize, PetscScalar( 0 ) );
395 // destroy memory
396 VecRestoreArray( ghostedVec_, &array );
397 }
398
399 // debugging; comes in handy to call these 2 methods in gdb
400 // doit is only here to prevent the compiler from optimizing these calls away...
401 void printGlobal ( bool doit )
402 {
403 if( !doit )
404 return;
405 VecView( vec_, PETSC_VIEWER_STDOUT_WORLD );
406 }
407
408 void printGhost ( bool doit)
409 {
410 if( !doit )
411 return;
412
413 PetscScalar *array;
414 VecGetArray( ghostedVec_,&array );
415 for( std::size_t i = 0; i < size(); i++ )
416 {
417 PetscSynchronizedPrintf(PETSC_COMM_WORLD,"%D %G\n",i,PetscRealPart(array[i]));
418 }
419 VecRestoreArray( ghostedVec_, &array );
420#if PETSC_VERSION_MAJOR <= 3 && PETSC_VERSION_MINOR < 5
421 PetscSynchronizedFlush( PETSC_COMM_WORLD );
422#else
423 PetscSynchronizedFlush( PETSC_COMM_WORLD, PETSC_STDOUT );
424#endif
425 }
426
427 // assign from other given PetscVector
428 void assign( const ThisType& other )
429 {
430 // we want the 'other' to do all its communication right now before
431 // we start copying values from it
432 other.communicateIfNecessary();
433
434 // copy vector entries
435 ::Dune::Petsc::VecCopy( other.vec_, vec_ );
436
437 // update ghost values
438 updateGhostRegions();
439 }
440
441 // assign from other given SimpleBlockVector with same block size
442 template <class Container>
443 void assignVector( const SimpleBlockVector< Container, blockSize >& other )
444 {
445 Vec& vec = *getGhostedVector();
446
447 // use mapping from the ghost mapper which removes duplicate dofs
448 const auto& mapping = mappers_.ghostMapper().mapping();
449 const size_t blocks = mapping.size();
450 assert( blocks == other.size() );
451 for( size_t b=0, bs = 0; b<blocks; ++b, bs += blockSize)
452 {
453 PetscInt block = mapping[ b ];
454 const PetscScalar* values = static_cast< const PetscScalar* > (other.data()+bs);
455 ::Dune::Petsc::VecSetValuesBlocked( vec, 1, &block, values, INSERT_VALUES );
456 }
457 ::Dune::Petsc::VecGhostGetLocalForm( vec_, &ghostedVec_ );
458
459 updateGhostRegions();
460 }
461
462 // assign from other given ISTLBlockVector with same block size
463 template <class DofBlock>
464 void assignVector( const ISTLBlockVector< DofBlock >& other )
465 {
466 assert( DofBlock :: dimension == blockSize );
467 Vec& vec = *getGhostedVector();
468
469 // use mapping from the ghost mapper which removes duplicate dofs
470 const auto& mapping = mappers_.ghostMapper().mapping();
471 const size_t blocks = mapping.size();
472 assert( blocks == other.size() );
473 for( size_t b=0; b<blocks; ++b )
474 {
475 PetscInt block = mapping[ b ];
476 const PetscScalar* values = static_cast< const PetscScalar* > (&(other[ b ][ 0 ])) ;
477 ::Dune::Petsc::VecSetValuesBlocked( vec, 1, &block, values, INSERT_VALUES );
478 }
479 ::Dune::Petsc::VecGhostGetLocalForm( vec_, &ghostedVec_ );
480
481 updateGhostRegions();
482 }
483
484 // assign from other given SimpleBlockVector with same block size
485 template <class Container>
486 void copyTo( SimpleBlockVector< Container, blockSize >& other ) const
487 {
488 typedef typename Container::FieldType FieldType;
489 const PetscScalar *array = nullptr;
490 VecGetArrayRead( ghostedVec_, &array );
491
492 // use mapping from the ghost mapper which removes duplicate dofs
493 const auto& mapping = mappers_.ghostMapper().mapping();
494 const size_t blocks = mapping.size();
495 assert( blocks == other.size() );
496 for( size_t b=0; b<blocks; ++b )
497 {
498 const PetscScalar* petscBlock = array + (blockSize * mapping[ b ]);
499 FieldType* otherBlock = other.data() + (b * blockSize);
500 for( int i=0; i<blockSize; ++i )
501 {
502 otherBlock[ i ] = petscBlock[ i ];
503 }
504 }
505 VecRestoreArrayRead( ghostedVec_, &array );
506 }
507
508 // assign from other given ISTLBlockVector with same block size
509 template <class DofBlock>
510 void copyTo ( ISTLBlockVector< DofBlock >& other ) const
511 {
512 assert( DofBlock :: dimension == blockSize );
513 const PetscScalar *array = nullptr;
514 VecGetArrayRead( ghostedVec_, &array );
515
516 // use mapping from the ghost mapper which removes duplicate dofs
517 const auto& mapping = mappers_.ghostMapper().mapping();
518 const size_t blocks = mapping.size();
519 assert( blocks == other.size() );
520 for( size_t b=0; b<blocks; ++b )
521 {
522 const PetscScalar* petscBlock = array + (blockSize * mapping[ b ]);
523 DofBlock& otherBlock = other[ b ];
524 for( int i=0; i<blockSize; ++i )
525 {
526 otherBlock[ i ] = petscBlock[ i ];
527 }
528 }
529 VecRestoreArrayRead( ghostedVec_, &array );
530 }
531
532 PetscVector& operator= ( const ThisType& other )
533 {
534 assign( other );
535 return *this;
536 }
537
538 const MappersType &mappers() const { return mappers_; }
539
540 std::size_t usedMemorySize() const
541 {
542 return size() * sizeof(value_type);
543 }
544
545 static void setMemoryFactor(const double memFactor)
546 {
547 // do nothing here
548 }
549
551 void memMoveBackward( const int length, const int oldStartIdx, const int newStartIdx)
552 {
553 DUNE_THROW(NotImplemented,"memMoveBackward is to be implemented");
554 }
555
557 void memMoveForward(const int length, const int oldStartIdx, const int newStartIdx)
558 {
559 DUNE_THROW(NotImplemented,"memMoveForward is to be implemented");
560 }
561
562 void copyContent( const int newIndex, const int oldIndex )
563 {
564 DUNE_THROW(NotImplemented,"copyContent is to be implemented");
565 }
566
567 protected:
568 const int getBackend( Vec vec ) const
569 {
570 VecType vt;
571 ::Dune::Petsc::VecGetType( vec, &vt );
572 // convert Petsc VecType to our id
573 return ::Dune::Petsc::Backend::toVecId( vt );
574 }
575
576 // setup vector according to mapping sizes
577 void init ()
578 {
579 mappers_.update();
580
581 const PetscInt localBlocks = mappers_.ghostMapper().interiorSize();
582 const PetscInt numGhostBlocks = mappers_.ghostMapper().ghostSize();
583
584 const PetscInt localSize = localBlocks * blockSize;
585 const PetscInt globalSize = mappers_.parallelMapper().size() * blockSize;
586
587 // finally, create the PETSc Vecs
588 const PetscInt *ghostBlocks = mappers_.parallelMapper().mapping().data() + localBlocks;
589 const auto& comm = mappers_.space().gridPart().comm();
590 if( blockSize == 1 )
591 ::Dune::Petsc::VecCreateGhost( comm, localSize, globalSize, numGhostBlocks, ghostBlocks, &vec_ );
592 else
593 ::Dune::Petsc::VecCreateGhostBlock( comm, blockSize, localSize, globalSize, numGhostBlocks, ghostBlocks, &vec_ );
594 ::Dune::Petsc::VecSetType( vec_, ::Dune::Petsc::Backend::toVecType( backend_ ) );
595 ::Dune::Petsc::VecGhostGetLocalForm( vec_, &ghostedVec_ );
596 }
597
598 // delete vectors
599 void removeObj()
600 {
601 ::Dune::Petsc::VecGhostRestoreLocalForm( vec_, &ghostedVec_ );
602 ::Dune::Petsc::VecDestroy( &vec_ );
603 }
604
605 // communicate using the space default communication option
606 void communicateIfNecessary () const
607 {
608 DefaultCommunicationOperationType op;
609 communicateIfNecessary( op );
610 }
611
612 template <class Operation>
613 void communicateIfNecessary (const Operation& op) const
614 {
615 // communicate this process' values
616 if( communicateFlag_ && memorySequence_ < sequence_ )
617 {
618 if ( memorySequence_ < sequence_ )
619 {
620 if ( Operation::value == DFCommunicationOperation::add )
621 {
622 ::Dune::Petsc::VecGhostUpdateBegin( vec_, ADD_VALUES, SCATTER_REVERSE );
623 ::Dune::Petsc::VecGhostUpdateEnd( vec_, ADD_VALUES, SCATTER_REVERSE );
624 }
625 ::Dune::Petsc::VecGhostUpdateBegin( vec_, INSERT_VALUES, SCATTER_FORWARD );
626 ::Dune::Petsc::VecGhostUpdateEnd( vec_, INSERT_VALUES, SCATTER_FORWARD );
627
628 memorySequence_ = sequence_;
629 }
630
631 communicateFlag_ = false;
632 }
633 }
634
635 // Updates the ghost dofs, obtains them from the owning process
636 void updateGhostRegions ()
637 {
638 ::Dune::Petsc::VecGhostUpdateBegin( vec_, INSERT_VALUES, SCATTER_FORWARD );
639 ::Dune::Petsc::VecGhostUpdateEnd( vec_, INSERT_VALUES, SCATTER_FORWARD );
640 }
641
642 void vectorIsUpToDateNow () const
643 {
644 memorySequence_ = sequence_;
645 communicateFlag_ = false;
646 }
647
648 /*
649 * data fields
650 */
651 MappersType mappers_;
652 Vec vec_;
653 Vec ghostedVec_;
654 const int backend_;
655
656 mutable unsigned long memorySequence_ = 0; // represents the state of the PETSc vec in memory
657 mutable unsigned long sequence_ = 0; // represents the modifications to the PETSc vec
658
659 mutable bool communicateFlag_ = false;
660 bool owner_;
661 };
662
663 } // namespace Fem
664
665} // namespace Dune
666
667#endif // #if HAVE_PETSC
668
669#endif // DUNE_FEM_PETSCVECTOR_HH
void communicate(CC &cc)
void axpy(const Ta &a, const type &y)
void init(const Matrix *matrix)
reference operator[](size_type i)
int size() const
iterator end()
void clear()
SLList< T, A > & operator=(const SLList< T, A > &other)
iterator begin()
bigunsignedint< k > & operator/=(const bigunsignedint< k > &x)
bigunsignedint< k > & operator+=(const bigunsignedint< k > &x)
bigunsignedint< k > & operator-=(const bigunsignedint< k > &x)
bigunsignedint< k > & operator*=(const bigunsignedint< k > &x)
friend friend auto operator*(const DiagonalMatrix &matrixA, const DiagonalMatrix< OtherScalar, n > &matrixB)
std::ptrdiff_t index() const
Iterator beforeBegin()
Iterator beforeEnd()
#define DUNE_THROW(E,...)
typename Impl::Index< Range >::Type IndexType
Definition hybrid.hh:69
const Grid & grid() const
const Communication & comm() const
int ghostSize(int codim) const
discrete function space
T endl(T... args)
T fill_n(T... args)