Debian Codegraph @

include/deal.II/lac/petsc_matrix_base.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2004 - 2024 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_petsc_matrix_base_h
16 #define dealii_petsc_matrix_base_h
17
18
19 #include <deal.II/base/config.h>
20
21 #ifdef DEAL_II_WITH_PETSC
22
23 # include <deal.II/base/enable_observer_pointer.h>
24
25 # include <deal.II/lac/exceptions.h>
26 # include <deal.II/lac/full_matrix.h>
27 # include <deal.II/lac/petsc_compatibility.h>
28 # include <deal.II/lac/petsc_vector_base.h>
29 # include <deal.II/lac/vector_operation.h>
30
31 # include <boost/container/small_vector.hpp>
32
33 # include <petscmat.h>
34
35 # include <cmath>
36 # include <memory>
37 # include <optional>
38 # include <vector>
39
40 DEAL_II_NAMESPACE_OPEN
41
42 // Forward declarations
43 # ifndef DOXYGEN
44 template <typename Matrix>
45 class BlockMatrixBase;
46 # endif
47
48
49 namespace PETScWrappers
50 {
51 // forward declarations
52 class MatrixBase;
53
54 namespace MatrixIterators
55 {
56 /**
57 * This class acts as an iterator walking over the elements of PETSc
58 * matrices. Since PETSc offers a uniform interface for all types of
59 * matrices, this iterator can be used to access both sparse and full
60 * matrices.
61 *
62 * Note that PETSc does not give any guarantees as to the order of
63 * elements within each row. Note also that accessing the elements of a
64 * full matrix surprisingly only shows the nonzero elements of the matrix,
65 * not all elements.
66 *
67 * @ingroup PETScWrappers
68 */
69 class const_iterator
70 {
71 # ifdef __CUDA_ARCH__
72 // NVCC, at least until 12.6, fails to compile the
73 // implementations of the nested Accessor class if
74 // it is declared as private. Work around this by
75 // making it public.
76 public:
77 # else
78 private:
79 # endif
80 /**
81 * Accessor class for iterators
82 */
83 class Accessor
84 {
85 public:
86 /**
87 * Declare type for container size.
88 */
89 using size_type = types::global_dof_index;
90
91 /**
92 * Constructor. Since we use accessors only for read access, a const
93 * matrix pointer is sufficient.
94 */
95 Accessor(const MatrixBase *matrix,
96 const size_type row,
97 const size_type index);
98
99 /**
100 * Row number of the element represented by this object.
101 */
102 size_type
103 row() const;
104
105 /**
106 * Index in row of the element represented by this object.
107 */
108 size_type
109 index() const;
110
111 /**
112 * Column number of the element represented by this object.
113 */
114 size_type
115 column() const;
116
117 /**
118 * Value of this matrix entry.
119 */
120 PetscScalar
121 value() const;
122
123 /**
124 * Exception
125 */
126 DeclException0(ExcBeyondEndOfMatrix);
127 /**
128 * Exception
129 */
130 DeclException3(ExcAccessToNonlocalRow,
131 int,
132 int,
133 int,
134 << "You tried to access row " << arg1
135 << " of a distributed matrix, but only rows " << arg2
136 << " through " << arg3
137 << " are stored locally and can be accessed.");
138
139 private:
140 /**
141 * The matrix accessed.
142 */
143 mutable MatrixBase *matrix;
144
145 /**
146 * Current row number.
147 */
148 size_type a_row;
149
150 /**
151 * Current index in row.
152 */
153 size_type a_index;
154
155 /**
156 * Cache where we store the column indices of the present row. This is
157 * necessary, since PETSc makes access to the elements of its matrices
158 * rather hard, and it is much more efficient to copy all column
159 * entries of a row once when we enter it than repeatedly asking PETSc
160 * for individual ones. This also makes some sense since it is likely
161 * that we will access them sequentially anyway.
162 *
163 * In order to make copying of iterators/accessor of acceptable
164 * performance, we keep a shared pointer to these entries so that more
165 * than one accessor can access this data if necessary.
166 */
167 std::shared_ptr<const std::vector<size_type>> colnum_cache;
168
169 /**
170 * Similar cache for the values of this row.
171 */
172 std::shared_ptr<const std::vector<PetscScalar>> value_cache;
173
174 /**
175 * Discard the old row caches (they may still be used by other
176 * accessors) and generate new ones for the row pointed to presently
177 * by this accessor.
178 */
179 void
180 visit_present_row();
181
182 // Make enclosing class a friend.
183 friend class const_iterator;
184 };
185
186 public:
187 /**
188 * Declare type for container size.
189 */
190 using size_type = types::global_dof_index;
191
192 /**
193 * Constructor. Create an iterator into the matrix @p matrix for the
194 * given row and the index within it.
195 */
196 const_iterator(const MatrixBase *matrix,
197 const size_type row,
198 const size_type index);
199
200 /**
201 * Prefix increment.
202 */
203 const_iterator &
204 operator++();
205
206 /**
207 * Postfix increment.
208 */
209 const_iterator
210 operator++(int);
211
212 /**
213 * Dereferencing operator.
214 */
215 const Accessor &
216 operator*() const;
217
218 /**
219 * Dereferencing operator.
220 */
221 const Accessor *
222 operator->() const;
223
224 /**
225 * Comparison. True, if both iterators point to the same matrix
226 * position.
227 */
228 bool
229 operator==(const const_iterator &) const;
230 /**
231 * Inverse of <tt>==</tt>.
232 */
233 bool
234 operator!=(const const_iterator &) const;
235
236 /**
237 * Comparison operator. Result is true if either the first row number is
238 * smaller or if the row numbers are equal and the first index is
239 * smaller.
240 */
241 bool
242 operator<(const const_iterator &) const;
243
244 /**
245 * Exception
246 */
247 DeclException2(ExcInvalidIndexWithinRow,
248 int,
249 int,
250 << "Attempt to access element " << arg2 << " of row "
251 << arg1 << " which doesn't have that many elements.");
252
253 private:
254 /**
255 * Store an object of the accessor class.
256 */
257 Accessor accessor;
258 };
259
260 } // namespace MatrixIterators
261
262
263 /**
264 * Base class for all matrix classes that are implemented on top of the
265 * PETSc matrix types. Since in PETSc all matrix types (i.e. sequential and
266 * parallel, sparse, blocked, etc.) are built by filling the contents of an
267 * abstract object that is only referenced through a pointer of a type that
268 * is independent of the actual matrix type, we can implement almost all
269 * functionality of matrices in this base class. Derived classes will then
270 * only have to provide the functionality to create one or the other kind of
271 * matrix.
272 *
273 * The interface of this class is modeled after the existing SparseMatrix
274 * class in deal.II. It has almost the same member functions, and is often
275 * exchangeable. However, since PETSc only supports a single scalar type
276 * (either double, float, or a complex data type), it is not templated, and
277 * only works with whatever your PETSc installation has defined the data
278 * type PetscScalar to.
279 *
280 * Note that PETSc only guarantees that operations do what you expect if the
281 * functions @p MatAssemblyBegin and @p MatAssemblyEnd have been called
282 * after matrix assembly. Therefore, you need to call
283 * SparseMatrix::compress() before you actually use the matrix. This also
284 * calls @p MatCompress that compresses the storage format for sparse
285 * matrices by discarding unused elements. PETSc allows to continue with
286 * assembling the matrix after calls to these functions, but since there are
287 * no more free entries available after that any more, it is better to only
288 * call SparseMatrix::compress() once at the end of the assembly stage and
289 * before the matrix is actively used.
290 *
291 * @ingroup PETScWrappers
292 * @ingroup Matrix1
293 */
294 class MatrixBase : public EnableObserverPointer
295 {
296 public:
297 /**
298 * Declare an alias for the iterator class.
299 */
300 using const_iterator = MatrixIterators::const_iterator;
301
302 /**
303 * Declare type for container size.
304 */
305 using size_type = types::global_dof_index;
306
307 /**
308 * Declare an alias in analogy to all the other container classes.
309 */
310 using value_type = PetscScalar;
311
312 /**
313 * Default constructor.
314 */
315 MatrixBase();
316
317 /**
318 * Initialize a Matrix from a PETSc Mat object. Note that we do not copy the
319 * matrix. Any PETSc object (including the Mat type) is in fact a reference
320 * counted pointer.
321 *
322 * A reference counted pointer is a type of pointer that maintains a
323 * reference count for the object it points to. The reference count is
324 * incremented each time a new reference to the object is created, and
325 * decremented each time a reference is destroyed. When the reference count
326 * reaches zero, the object is automatically deleted, freeing up the memory
327 * it was using.
328 *
329 * In the context of PETSc, reference counted pointers are used to manage
330 * the memory of objects such as vectors, matrices, and solvers. By using
331 * reference counted pointers, PETSc ensures that memory is automatically
332 * released when it is no longer needed, without the need for explicit
333 * memory management.
334 */
335 explicit MatrixBase(const Mat &);
336
337 /**
338 * Copy constructor. It is deleted as copying this base class
339 * without knowing the concrete kind of matrix stored may both
340 * miss important details and be expensive if the matrix is large.
341 */
342 MatrixBase(const MatrixBase &) = delete;
343
344 /**
345 * Copy operator. It is deleted as copying this base class
346 * without knowing the concrete kind of matrix stored may both
347 * miss important details and be expensive if the matrix is large.
348 */
349 MatrixBase &
350 operator=(const MatrixBase &) = delete;
351
352 /**
353 * Destructor. Made virtual so that one can use pointers to this class.
354 */
355 virtual ~MatrixBase() override;
356
357 /**
358 * This method associates the PETSc Mat to the instance of the class.
359 * This is particularly useful when performing PETSc to Deal.II operations
360 * since it allows to reuse the Deal.II MatrixBase and the PETSc Mat
361 * without incurring in memory copies.
362 */
363 void
364 reinit(Mat A);
365
366 /**
367 * This operator assigns a scalar to a matrix. Since this does usually not
368 * make much sense (should we set all matrix entries to this value? Only
369 * the nonzero entries of the sparsity pattern?), this operation is only
370 * allowed if the actual value to be assigned is zero. This operator only
371 * exists to allow for the obvious notation <tt>matrix=0</tt>, which sets
372 * all elements of the matrix to zero, but keeps the sparsity pattern
373 * previously used.
374 */
375 MatrixBase &
376 operator=(const value_type d);
377
378 /**
379 * Release all memory and return to a state just like after having called
380 * the default constructor.
381 */
382 void
383 clear();
384
385 /**
386 * Set the element (<i>i,j</i>) to @p value.
387 *
388 * If the present object (from a derived class of this one) happens to be
389 * a sparse matrix, then this function adds a new entry to the matrix if
390 * it didn't exist before, very much in contrast to the SparseMatrix class
391 * which throws an error if the entry does not exist. If <tt>value</tt> is
392 * not a finite number an exception is thrown.
393 */
394 void
395 set(const size_type i, const size_type j, const PetscScalar value);
396
397 /**
398 * Set all elements given in a FullMatrix<double> into the sparse matrix
399 * locations given by <tt>indices</tt>. In other words, this function
400 * writes the elements in <tt>full_matrix</tt> into the calling matrix,
401 * using the local-to-global indexing specified by <tt>indices</tt> for
402 * both the rows and the columns of the matrix. This function assumes a
403 * quadratic sparse matrix and a quadratic full_matrix, the usual
404 * situation in FE calculations.
405 *
406 * If the present object (from a derived class of this one) happens to be
407 * a sparse matrix, then this function adds some new entries to the matrix
408 * if they didn't exist before, very much in contrast to the SparseMatrix
409 * class which throws an error if the entry does not exist.
410 *
411 * The optional parameter <tt>elide_zero_values</tt> can be used to
412 * specify whether zero values should be inserted anyway or they should be
413 * filtered away. The default value is <tt>false</tt>, i.e., even zero
414 * values are inserted/replaced.
415 */
416 void
417 set(const std::vector<size_type> &indices,
418 const FullMatrix<PetscScalar> &full_matrix,
419 const bool elide_zero_values = false);
420
421 /**
422 * Same function as before, but now including the possibility to use
423 * rectangular full_matrices and different local-to-global indexing on
424 * rows and columns, respectively.
425 */
426 void
427 set(const std::vector<size_type> &row_indices,
428 const std::vector<size_type> &col_indices,
429 const FullMatrix<PetscScalar> &full_matrix,
430 const bool elide_zero_values = false);
431
432 /**
433 * Set several elements in the specified row of the matrix with column
434 * indices as given by <tt>col_indices</tt> to the respective value.
435 *
436 * If the present object (from a derived class of this one) happens to be
437 * a sparse matrix, then this function adds some new entries to the matrix
438 * if they didn't exist before, very much in contrast to the SparseMatrix
439 * class which throws an error if the entry does not exist.
440 *
441 * The optional parameter <tt>elide_zero_values</tt> can be used to
442 * specify whether zero values should be inserted anyway or they should be
443 * filtered away. The default value is <tt>false</tt>, i.e., even zero
444 * values are inserted/replaced.
445 */
446 void
447 set(const size_type row,
448 const std::vector<size_type> &col_indices,
449 const std::vector<PetscScalar> &values,
450 const bool elide_zero_values = false);
451
452 /**
453 * Set several elements to values given by <tt>values</tt> in a given row
454 * in columns given by col_indices into the sparse matrix.
455 *
456 * If the present object (from a derived class of this one) happens to be
457 * a sparse matrix, then this function adds some new entries to the matrix
458 * if they didn't exist before, very much in contrast to the SparseMatrix
459 * class which throws an error if the entry does not exist.
460 *
461 * The optional parameter <tt>elide_zero_values</tt> can be used to
462 * specify whether zero values should be inserted anyway or they should be
463 * filtered away. The default value is <tt>false</tt>, i.e., even zero
464 * values are inserted/replaced.
465 */
466 void
467 set(const size_type row,
468 const size_type n_cols,
469 const size_type *col_indices,
470 const PetscScalar *values,
471 const bool elide_zero_values = false);
472
473 /**
474 * Add @p value to the element (<i>i,j</i>).
475 *
476 * If the present object (from a derived class of this one) happens to be
477 * a sparse matrix, then this function adds a new entry to the matrix if
478 * it didn't exist before, very much in contrast to the SparseMatrix class
479 * which throws an error if the entry does not exist. If <tt>value</tt> is
480 * not a finite number an exception is thrown.
481 */
482 void
483 add(const size_type i, const size_type j, const PetscScalar value);
484
485 /**
486 * Add all elements given in a FullMatrix<double> into sparse matrix
487 * locations given by <tt>indices</tt>. In other words, this function adds
488 * the elements in <tt>full_matrix</tt> to the respective entries in
489 * calling matrix, using the local-to-global indexing specified by
490 * <tt>indices</tt> for both the rows and the columns of the matrix. This
491 * function assumes a quadratic sparse matrix and a quadratic full_matrix,
492 * the usual situation in FE calculations.
493 *
494 * If the present object (from a derived class of this one) happens to be
495 * a sparse matrix, then this function adds some new entries to the matrix
496 * if they didn't exist before, very much in contrast to the SparseMatrix
497 * class which throws an error if the entry does not exist.
498 *
499 * The optional parameter <tt>elide_zero_values</tt> can be used to
500 * specify whether zero values should be added anyway or these should be
501 * filtered away and only non-zero data is added. The default value is
502 * <tt>true</tt>, i.e., zero values won't be added into the matrix.
503 */
504 void
505 add(const std::vector<size_type> &indices,
506 const FullMatrix<PetscScalar> &full_matrix,
507 const bool elide_zero_values = true);
508
509 /**
510 * Same function as before, but now including the possibility to use
511 * rectangular full_matrices and different local-to-global indexing on
512 * rows and columns, respectively.
513 */
514 void
515 add(const std::vector<size_type> &row_indices,
516 const std::vector<size_type> &col_indices,
517 const FullMatrix<PetscScalar> &full_matrix,
518 const bool elide_zero_values = true);
519
520 /**
521 * Set several elements in the specified row of the matrix with column
522 * indices as given by <tt>col_indices</tt> to the respective value.
523 *
524 * If the present object (from a derived class of this one) happens to be
525 * a sparse matrix, then this function adds some new entries to the matrix
526 * if they didn't exist before, very much in contrast to the SparseMatrix
527 * class which throws an error if the entry does not exist.
528 *
529 * The optional parameter <tt>elide_zero_values</tt> can be used to
530 * specify whether zero values should be added anyway or these should be
531 * filtered away and only non-zero data is added. The default value is
532 * <tt>true</tt>, i.e., zero values won't be added into the matrix.
533 */
534 void
535 add(const size_type row,
536 const std::vector<size_type> &col_indices,
537 const std::vector<PetscScalar> &values,
538 const bool elide_zero_values = true);
539
540 /**
541 * Add an array of values given by <tt>values</tt> in the given global
542 * matrix row at columns specified by col_indices in the sparse matrix.
543 *
544 * If the present object (from a derived class of this one) happens to be
545 * a sparse matrix, then this function adds some new entries to the matrix
546 * if they didn't exist before, very much in contrast to the SparseMatrix
547 * class which throws an error if the entry does not exist.
548 *
549 * The optional parameter <tt>elide_zero_values</tt> can be used to
550 * specify whether zero values should be added anyway or these should be
551 * filtered away and only non-zero data is added. The default value is
552 * <tt>true</tt>, i.e., zero values won't be added into the matrix.
553 */
554 void
555 add(const size_type row,
556 const size_type n_cols,
557 const size_type *col_indices,
558 const PetscScalar *values,
559 const bool elide_zero_values = true,
560 const bool col_indices_are_sorted = false);
561
562 /**
563 * Remove all elements from this <tt>row</tt> by setting them to zero. The
564 * function does not modify the number of allocated nonzero entries, it
565 * only sets some entries to zero. It may drop them from the sparsity
566 * pattern, though (but retains the allocated memory in case new entries
567 * are again added later).
568 *
569 * This operation is used in eliminating constraints (e.g. due to hanging
570 * nodes) and makes sure that we can write this modification to the matrix
571 * without having to read entries (such as the locations of non-zero
572 * elements) from it -- without this operation, removing constraints on
573 * parallel matrices is a rather complicated procedure.
574 *
575 * The second parameter can be used to set the diagonal entry of this row
576 * to a value different from zero. The default is to set it to zero.
577 */
578 void
579 clear_row(const size_type row, const PetscScalar new_diag_value = 0);
580
581 /**
582 * Same as clear_row(), except that it works on a number of rows at once.
583 *
584 * The second parameter can be used to set the diagonal entries of all
585 * cleared rows to something different from zero. Note that all of these
586 * diagonal entries get the same value -- if you want different values for
587 * the diagonal entries, you have to set them by hand.
588 */
589 void
590 clear_rows(const ArrayView<const size_type> &rows,
591 const PetscScalar new_diag_value = 0);
592
593 /**
594 * Same as clear_rows(), except that the function also zeros the columns.
595 */
596 void
597 clear_rows_columns(const std::vector<size_type> &row_and_column_indices,
598 const PetscScalar new_diag_value = 0);
599
600 /**
601 * PETSc matrices store their own sparsity patterns. So, in analogy to our
602 * own SparsityPattern class, this function compresses the sparsity
603 * pattern and allows the resulting matrix to be used in all other
604 * operations where before only assembly functions were allowed. This
605 * function must therefore be called once you have assembled the matrix.
606 *
607 * See
608 * @ref GlossCompress "Compressing distributed objects"
609 * for more information.
610 */
611 void
612 compress(const VectorOperation::values operation);
613
614 /**
615 * Return the value of the entry (<i>i,j</i>). This may be an expensive
616 * operation and you should always take care where to call this function.
617 * In contrast to the respective function in the @p MatrixBase class, we
618 * don't throw an exception if the respective entry doesn't exist in the
619 * sparsity pattern of this class, since PETSc does not transmit this
620 * information.
621 *
622 * This function is therefore exactly equivalent to the <tt>el()</tt>
623 * function.
624 */
625 PetscScalar
626 operator()(const size_type i, const size_type j) const;
627
628 /**
629 * Return the value of the matrix entry (<i>i,j</i>). If this entry does
630 * not exist in the sparsity pattern, then zero is returned. While this
631 * may be convenient in some cases, note that it is simple to write
632 * algorithms that are slow compared to an optimal solution, since the
633 * sparsity of the matrix is not used.
634 */
635 PetscScalar
636 el(const size_type i, const size_type j) const;
637
638 /**
639 * Return the main diagonal element in the <i>i</i>th row. This function
640 * throws an error if the matrix is not quadratic.
641 *
642 * Since we do not have direct access to the underlying data structure,
643 * this function is no faster than the elementwise access using the el()
644 * function. However, we provide this function for compatibility with the
645 * SparseMatrix class.
646 */
647 PetscScalar
648 diag_element(const size_type i) const;
649
650 /**
651 * Return the number of rows in this matrix.
652 */
653 size_type
654 m() const;
655
656 /**
657 * Return the number of columns in this matrix.
658 */
659 size_type
660 n() const;
661
662 /**
663 * Return the local dimension of the matrix, i.e. the number of rows
664 * stored on the present MPI process. For sequential matrices, this number
665 * is the same as m(), but for parallel matrices it may be smaller.
666 *
667 * To figure out which elements exactly are stored locally, use
668 * local_range().
669 */
670 size_type
671 local_size() const;
672
673 /**
674 * Return a pair of indices indicating which rows of this matrix are
675 * stored locally. The first number is the index of the first row stored,
676 * the second the index of the one past the last one that is stored
677 * locally. If this is a sequential matrix, then the result will be the
678 * pair (0,m()), otherwise it will be a pair (i,i+n), where
679 * <tt>n=local_size()</tt>.
680 */
681 std::pair<size_type, size_type>
682 local_range() const;
683
684 /**
685 * Return whether @p index is in the local range or not, see also
686 * local_range().
687 */
688 bool
689 in_local_range(const size_type index) const;
690
691 /**
692 * Return the local number of columns stored on the present MPI process.
693 *
694 * To figure out which elements exactly are stored locally, use
695 * local_domain().
696 */
697 size_type
698 local_domain_size() const;
699
700 /**
701 * Return a pair of indices indicating which columns of this matrix are
702 * stored locally. The first number is the index of the first column stored,
703 * the second the index of the one past the last one that is stored
704 * locally.
705 */
706 std::pair<size_type, size_type>
707 local_domain() const;
708
709 /**
710 * Return the underlying MPI communicator.
711 */
712 MPI_Comm
713 get_mpi_communicator() const;
714
715 /**
716 * Return the number of nonzero elements of this matrix. Actually, it
717 * returns the number of entries in the sparsity pattern; if any of the
718 * entries should happen to be zero, it is counted anyway.
719 */
720 std::uint64_t
721 n_nonzero_elements() const;
722
723 /**
724 * Number of entries in a specific row.
725 */
726 size_type
727 row_length(const size_type row) const;
728
729 /**
730 * Return the l1-norm of the matrix, that is $|M|_1=max_{all columns
731 * j}\sum_{all rows i} |M_ij|$, (max. sum of columns). This is the natural
732 * matrix norm that is compatible to the l1-norm for vectors, i.e.
733 * $|Mv|_1\leq |M|_1 |v|_1$. (cf. Haemmerlin-Hoffmann: Numerische
734 * Mathematik)
735 */
736 PetscReal
737 l1_norm() const;
738
739 /**
740 * Return the linfty-norm of the matrix, that is $|M|_infty=max_{all rows
741 * i}\sum_{all columns j} |M_ij|$, (max. sum of rows). This is the natural
742 * matrix norm that is compatible to the linfty-norm of vectors, i.e.
743 * $|Mv|_infty \leq |M|_infty |v|_infty$. (cf. Haemmerlin-Hoffmann:
744 * Numerische Mathematik)
745 */
746 PetscReal
747 linfty_norm() const;
748
749 /**
750 * Return the frobenius norm of the matrix, i.e. the square root of the
751 * sum of squares of all entries in the matrix.
752 */
753 PetscReal
754 frobenius_norm() const;
755
756
757 /**
758 * Return the square of the norm of the vector $v$ with respect to the
759 * norm induced by this matrix, i.e. $\left(v,Mv\right)$. This is useful,
760 * e.g. in the finite element context, where the $L_2$ norm of a function
761 * equals the matrix norm with respect to the @ref GlossMassMatrix "mass matrix" of the vector
762 * representing the nodal values of the finite element function.
763 *
764 * Obviously, the matrix needs to be quadratic for this operation.
765 *
766 * The implementation of this function is not as efficient as the one in
767 * the @p MatrixBase class used in deal.II (i.e. the original one, not the
768 * PETSc wrapper class) since PETSc doesn't support this operation and
769 * needs a temporary vector.
770 *
771 * Note that if the current object represents a parallel distributed
772 * matrix (of type PETScWrappers::MPI::SparseMatrix), then the given
773 * vector has to be a distributed vector as well. Conversely, if the
774 * matrix is not distributed, then neither may the vector be.
775 */
776 PetscScalar
777 matrix_norm_square(const VectorBase &v) const;
778
779
780 /**
781 * Compute the matrix scalar product $\left(u,Mv\right)$.
782 *
783 * The implementation of this function is not as efficient as the one in
784 * the @p MatrixBase class used in deal.II (i.e. the original one, not the
785 * PETSc wrapper class) since PETSc doesn't support this operation and
786 * needs a temporary vector.
787 *
788 * Note that if the current object represents a parallel distributed
789 * matrix (of type PETScWrappers::MPI::SparseMatrix), then both vectors
790 * have to be distributed vectors as well. Conversely, if the matrix is
791 * not distributed, then neither of the vectors may be.
792 */
793 PetscScalar
794 matrix_scalar_product(const VectorBase &u, const VectorBase &v) const;
795
796 /**
797 * Return the trace of the matrix, i.e. the sum of all diagonal entries in
798 * the matrix.
799 */
800 PetscScalar
801 trace() const;
802
803 /**
804 * Multiply the entire matrix by a fixed factor.
805 */
806 MatrixBase &
807 operator*=(const PetscScalar factor);
808
809 /**
810 * Divide the entire matrix by a fixed factor.
811 */
812 MatrixBase &
813 operator/=(const PetscScalar factor);
814
815
816 /**
817 * Add the matrix @p other scaled by the factor @p factor to the current
818 * matrix.
819 */
820 MatrixBase &
821 add(const PetscScalar factor, const MatrixBase &other);
822
823 /**
824 * Matrix-vector multiplication: let <i>dst = M*src</i> with <i>M</i>
825 * being this matrix.
826 *
827 * Source and destination must not be the same vector.
828 *
829 * Note that if the current object represents a parallel distributed
830 * matrix (of type PETScWrappers::MPI::SparseMatrix), then both vectors
831 * have to be distributed vectors as well. Conversely, if the matrix is
832 * not distributed, then neither of the vectors may be.
833 */
834 void
835 vmult(VectorBase &dst, const VectorBase &src) const;
836
837 /**
838 * Matrix-vector multiplication: let <i>dst = M<sup>T</sup>*src</i> with
839 * <i>M</i> being this matrix. This function does the same as vmult() but
840 * takes the transposed matrix.
841 *
842 * Source and destination must not be the same vector.
843 *
844 * Note that if the current object represents a parallel distributed
845 * matrix (of type PETScWrappers::MPI::SparseMatrix), then both vectors
846 * have to be distributed vectors as well. Conversely, if the matrix is
847 * not distributed, then neither of the vectors may be.
848 */
849 void
850 Tvmult(VectorBase &dst, const VectorBase &src) const;
851
852 /**
853 * Adding Matrix-vector multiplication. Add <i>M*src</i> on <i>dst</i>
854 * with <i>M</i> being this matrix.
855 *
856 * Source and destination must not be the same vector.
857 *
858 * Note that if the current object represents a parallel distributed
859 * matrix (of type PETScWrappers::MPI::SparseMatrix), then both vectors
860 * have to be distributed vectors as well. Conversely, if the matrix is
861 * not distributed, then neither of the vectors may be.
862 */
863 void
864 vmult_add(VectorBase &dst, const VectorBase &src) const;
865
866 /**
867 * Adding Matrix-vector multiplication. Add <i>M<sup>T</sup>*src</i> to
868 * <i>dst</i> with <i>M</i> being this matrix. This function does the same
869 * as vmult_add() but takes the transposed matrix.
870 *
871 * Source and destination must not be the same vector.
872 *
873 * Note that if the current object represents a parallel distributed
874 * matrix (of type PETScWrappers::MPI::SparseMatrix), then both vectors
875 * have to be distributed vectors as well. Conversely, if the matrix is
876 * not distributed, then neither of the vectors may be.
877 */
878 void
879 Tvmult_add(VectorBase &dst, const VectorBase &src) const;
880
881 /**
882 * Compute the residual of an equation <i>Mx=b</i>, where the residual is
883 * defined to be <i>r=b-Mx</i>. Write the residual into @p dst. The
884 * <i>l<sub>2</sub></i> norm of the residual vector is returned.
885 *
886 * Source <i>x</i> and destination <i>dst</i> must not be the same vector.
887 *
888 * Note that if the current object represents a parallel distributed
889 * matrix (of type PETScWrappers::MPI::SparseMatrix), then all vectors
890 * have to be distributed vectors as well. Conversely, if the matrix is
891 * not distributed, then neither of the vectors may be.
892 */
893 PetscScalar
894 residual(VectorBase &dst, const VectorBase &x, const VectorBase &b) const;
895
896 /**
897 * Iterator starting at the first entry. This can only be called on a
898 * processor owning the entire matrix. In all other cases refer to the
899 * version of begin() taking a row number as an argument.
900 */
901 const_iterator
902 begin() const;
903
904 /**
905 * Final iterator. This can only be called on a processor owning the entire
906 * matrix. In all other cases refer to the version of end() taking a row
907 * number as an argument.
908 */
909 const_iterator
910 end() const;
911
912 /**
913 * Iterator starting at the first entry of row @p r.
914 *
915 * Note that if the given row is empty, i.e. does not contain any nonzero
916 * entries, then the iterator returned by this function equals
917 * <tt>end(r)</tt>. Note also that the iterator may not be dereferenceable
918 * in that case.
919 */
920 const_iterator
921 begin(const size_type r) const;
922
923 /**
924 * Final iterator of row <tt>r</tt>. It points to the first element past
925 * the end of line @p r, or past the end of the entire sparsity pattern.
926 *
927 * Note that the end iterator is not necessarily dereferenceable. This is
928 * in particular the case if it is the end iterator for the last row of a
929 * matrix.
930 */
931 const_iterator
932 end(const size_type r) const;
933
934 /**
935 * Conversion operator to gain access to the underlying PETSc type. If you
936 * do this, you cut this class off some information it may need, so this
937 * conversion operator should only be used if you know what you do. In
938 * particular, it should only be used for read-only operations into the
939 * matrix.
940 */
941 operator Mat() const;
942
943 /**
944 * Return a reference to the underlying PETSc type. It can be used to
945 * modify the underlying data, so use it only when you know what you
946 * are doing.
947 */
948 Mat &
949 petsc_matrix();
950
951 /**
952 * Make an in-place transpose of a matrix.
953 */
954 void
955 transpose();
956
957 /**
958 * Test whether a matrix is symmetric. Default tolerance is
959 * $1000\times32$-bit machine precision.
960 */
961 PetscBool
962 is_symmetric(const double tolerance = 1.e-12);
963
964 /**
965 * Test whether a matrix is Hermitian, i.e. it is the complex conjugate of
966 * its transpose. Default tolerance is $1000\times32$-bit machine
967 * precision.
968 */
969 PetscBool
970 is_hermitian(const double tolerance = 1.e-12);
971
972 /**
973 * Print the PETSc matrix object values using PETSc internal matrix viewer
974 * function <tt>MatView</tt>. The default format prints the non- zero
975 * matrix elements. For other valid view formats, consult
976 * http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/Mat/MatView.html
977 */
978 void
979 write_ascii(const PetscViewerFormat format = PETSC_VIEWER_DEFAULT);
980
981 /**
982 * Print the elements of a matrix to the given output stream.
983 *
984 * @param[in,out] out The output stream to which to write.
985 * @param[in] alternative_output This argument is ignored. It exists for
986 * compatibility with similar functions in other matrix classes.
987 */
988 void
989 print(std::ostream &out, const bool alternative_output = false) const;
990
991 /**
992 * Return the number bytes consumed by this matrix on this CPU.
993 */
994 std::size_t
995 memory_consumption() const;
996
997 /**
998 * Exception
999 */
1000 DeclExceptionMsg(ExcSourceEqualsDestination,
1001 "You are attempting an operation on two vectors that "
1002 "are the same object, but the operation requires that the "
1003 "two objects are in fact different.");
1004
1005 /**
1006 * Exception.
1007 */
1008 DeclException2(ExcWrongMode,
1009 int,
1010 int,
1011 << "You tried to do a "
1012 << (arg1 == 1 ? "'set'" : (arg1 == 2 ? "'add'" : "???"))
1013 << " operation but the matrix is currently in "
1014 << (arg2 == 1 ? "'set'" : (arg2 == 2 ? "'add'" : "???"))
1015 << " mode. You first have to call 'compress()'.");
1016
1017 protected:
1018 /**
1019 * A generic matrix object in PETSc. The actual type, a sparse matrix, is
1020 * set in the constructor.
1021 */
1022 Mat matrix;
1023
1024 /**
1025 * Store whether the last action was a write or add operation.
1026 */
1027 VectorOperation::values last_action;
1028
1029 /**
1030 * Ensure that the add/set mode that is required for actions following
1031 * this call is compatible with the current mode. Should be called from
1032 * all internal functions accessing matrix elements.
1033 */
1034 void
1035 prepare_action(const VectorOperation::values new_action);
1036
1037 /**
1038 * Internal function that checks that there are no pending insert/add
1039 * operations. Throws an exception otherwise. Useful before calling any
1040 * PETSc internal functions modifying the matrix.
1041 */
1042 void
1043 assert_is_compressed();
1044
1045 /**
1046 * For some matrix storage formats, in particular for the PETSc
1047 * distributed blockmatrices, set and add operations on individual
1048 * elements can not be freely mixed. Rather, one has to synchronize
1049 * operations when one wants to switch from setting elements to adding to
1050 * elements. BlockMatrixBase automatically synchronizes the access by
1051 * calling this helper function for each block. This function ensures that
1052 * the matrix is in a state that allows adding elements; if it previously
1053 * already was in this state, the function does nothing.
1054 */
1055 void
1056 prepare_add();
1057 /**
1058 * Same as prepare_add() but prepare the matrix for setting elements if
1059 * the representation of elements in this class requires such an
1060 * operation.
1061 */
1062 void
1063 prepare_set();
1064
1065 /**
1066 * Base function to perform the matrix-matrix multiplication $C = AB$,
1067 * or, if a vector $V$ whose size is compatible with B is given,
1068 * $C = A \text{diag}(V) B$, where $\text{diag}(V)$ defines a
1069 * diagonal matrix with the vector entries.
1070 *
1071 * This function assumes that the calling matrix $A$ and $B$
1072 * have compatible sizes. The size of $C$ will be set within this
1073 * function.
1074 *
1075 * The content as well as the sparsity pattern of the matrix $C$ will be
1076 * reset by this function, so make sure that the sparsity pattern is not
1077 * used somewhere else in your program. This is an expensive operation, so
1078 * think twice before you use this function.
1079 */
1080 void
1081 mmult(MatrixBase &C, const MatrixBase &B, const VectorBase &V) const;
1082
1083 /**
1084 * Base function to perform the matrix-matrix multiplication with
1085 * the transpose of <tt>this</tt>, i.e., $C = A^T B$, or,
1086 * if an optional vector $V$ whose size is compatible with $B$ is given,
1087 * $C = A^T \text{diag}(V) B$, where $\text{diag}(V)$ defines a
1088 * diagonal matrix with the vector entries.
1089 *
1090 * This function assumes that the calling matrix $A$ and $B$
1091 * have compatible sizes. The size of $C$ will be set within this
1092 * function.
1093 *
1094 * The content as well as the sparsity pattern of the matrix $C$ will be
1095 * changed by this function, so make sure that the sparsity pattern is not
1096 * used somewhere else in your program. This is an expensive operation, so
1097 * think twice before you use this function.
1098 */
1099 void
1100 Tmmult(MatrixBase &C, const MatrixBase &B, const VectorBase &V) const;
1101
1102 private:
1103 // To allow calling protected prepare_add() and prepare_set().
1104 template <class>
1105 friend class dealii::BlockMatrixBase;
1106
1107
1108 /**
1109 * Internal function wrapping MatSetValues().
1110 */
1111 void
1112 add_or_set(const VectorOperation::values &operation,
1113 const size_type row,
1114 const size_type n_cols,
1115 const size_type *col_indices,
1116 const PetscScalar *values,
1117 const bool elide_zero_values);
1118 };
1119
1120
1121
1122 # ifndef DOXYGEN
1123 // ---------------------- inline and template functions ---------------------
1124
1125
1126 namespace MatrixIterators
1127 {
1128 inline const_iterator::Accessor::Accessor(const MatrixBase *matrix,
1129 const size_type row,
1130 const size_type index)
1131 : matrix(const_cast<MatrixBase *>(matrix))
1132 , a_row(row)
1133 , a_index(index)
1134 {
1135 visit_present_row();
1136 }
1137
1138
1139
1140 inline const_iterator::Accessor::size_type
1141 const_iterator::Accessor::row() const
1142 {
1143 Assert(a_row < matrix->m(), ExcBeyondEndOfMatrix());
1144 return a_row;
1145 }
1146
1147
1148 inline const_iterator::Accessor::size_type
1149 const_iterator::Accessor::column() const
1150 {
1151 Assert(a_row < matrix->m(), ExcBeyondEndOfMatrix());
1152 return (*colnum_cache)[a_index];
1153 }
1154
1155
1156 inline const_iterator::Accessor::size_type
1157 const_iterator::Accessor::index() const
1158 {
1159 Assert(a_row < matrix->m(), ExcBeyondEndOfMatrix());
1160 return a_index;
1161 }
1162
1163
1164 inline PetscScalar
1165 const_iterator::Accessor::value() const
1166 {
1167 Assert(a_row < matrix->m(), ExcBeyondEndOfMatrix());
1168 return (*value_cache)[a_index];
1169 }
1170
1171
1172 inline const_iterator::const_iterator(const MatrixBase *matrix,
1173 const size_type row,
1174 const size_type index)
1175 : accessor(matrix, row, index)
1176 {}
1177
1178
1179
1180 inline const_iterator &
1181 const_iterator::operator++()
1182 {
1183 Assert(accessor.a_row < accessor.matrix->m(), ExcIteratorPastEnd());
1184
1185 ++accessor.a_index;
1186
1187 // if at end of line: do one step, then cycle until we find a
1188 // row with a nonzero number of entries
1189 if (accessor.a_index >= accessor.colnum_cache->size())
1190 {
1191 accessor.a_index = 0;
1192 ++accessor.a_row;
1193
1194 while ((accessor.a_row < accessor.matrix->m()) &&
1195 (accessor.a_row < accessor.matrix->local_range().second) &&
1196 (accessor.matrix->row_length(accessor.a_row) == 0))
1197 ++accessor.a_row;
1198
1199 accessor.visit_present_row();
1200 }
1201 return *this;
1202 }
1203
1204
1205 inline const_iterator
1206 const_iterator::operator++(int)
1207 {
1208 const const_iterator old_state = *this;
1209 ++(*this);
1210 return old_state;
1211 }
1212
1213
1214 inline const const_iterator::Accessor &
1215 const_iterator::operator*() const
1216 {
1217 return accessor;
1218 }
1219
1220
1221 inline const const_iterator::Accessor *
1222 const_iterator::operator->() const
1223 {
1224 return &accessor;
1225 }
1226
1227
1228 inline bool
1229 const_iterator::operator==(const const_iterator &other) const
1230 {
1231 return (accessor.a_row == other.accessor.a_row &&
1232 accessor.a_index == other.accessor.a_index);
1233 }
1234
1235
1236 inline bool
1237 const_iterator::operator!=(const const_iterator &other) const
1238 {
1239 return !(*this == other);
1240 }
1241
1242
1243 inline bool
1244 const_iterator::operator<(const const_iterator &other) const
1245 {
1246 return (accessor.row() < other.accessor.row() ||
1247 (accessor.row() == other.accessor.row() &&
1248 accessor.index() < other.accessor.index()));
1249 }
1250
1251 } // namespace MatrixIterators
1252
1253
1254
1255 // Inline the set() and add()
1256 // functions, since they will be
1257 // called frequently, and the
1258 // compiler can optimize away
1259 // some unnecessary loops when
1260 // the sizes are given at
1261 // compile time.
1262 inline void
1263 MatrixBase::set(const size_type i, const size_type j, const PetscScalar value)
1264 {
1265 AssertIsFinite(value);
1266
1267 set(i, 1, &j, &value, false);
1268 }
1269
1270
1271
1272 inline void
1273 MatrixBase::set(const std::vector<size_type> &indices,
1274 const FullMatrix<PetscScalar> &values,
1275 const bool elide_zero_values)
1276 {
1277 Assert(indices.size() == values.m(),
1278 ExcDimensionMismatch(indices.size(), values.m()));
1279 Assert(values.m() == values.n(), ExcNotQuadratic());
1280
1281 for (size_type i = 0; i < indices.size(); ++i)
1282 set(indices[i],
1283 indices.size(),
1284 indices.data(),
1285 &values(i, 0),
1286 elide_zero_values);
1287 }
1288
1289
1290
1291 inline void
1292 MatrixBase::set(const std::vector<size_type> &row_indices,
1293 const std::vector<size_type> &col_indices,
1294 const FullMatrix<PetscScalar> &values,
1295 const bool elide_zero_values)
1296 {
1297 Assert(row_indices.size() == values.m(),
1298 ExcDimensionMismatch(row_indices.size(), values.m()));
1299 Assert(col_indices.size() == values.n(),
1300 ExcDimensionMismatch(col_indices.size(), values.n()));
1301
1302 for (size_type i = 0; i < row_indices.size(); ++i)
1303 set(row_indices[i],
1304 col_indices.size(),
1305 col_indices.data(),
1306 &values(i, 0),
1307 elide_zero_values);
1308 }
1309
1310
1311
1312 inline void
1313 MatrixBase::set(const size_type row,
1314 const std::vector<size_type> &col_indices,
1315 const std::vector<PetscScalar> &values,
1316 const bool elide_zero_values)
1317 {
1318 Assert(col_indices.size() == values.size(),
1319 ExcDimensionMismatch(col_indices.size(), values.size()));
1320
1321 set(row,
1322 col_indices.size(),
1323 col_indices.data(),
1324 values.data(),
1325 elide_zero_values);
1326 }
1327
1328
1329
1330 inline void
1331 MatrixBase::set(const size_type row,
1332 const size_type n_cols,
1333 const size_type *col_indices,
1334 const PetscScalar *values,
1335 const bool elide_zero_values)
1336 {
1337 add_or_set(VectorOperation::insert,
1338 row,
1339 n_cols,
1340 col_indices,
1341 values,
1342 elide_zero_values);
1343 }
1344
1345
1346
1347 inline void
1348 MatrixBase::add(const size_type i, const size_type j, const PetscScalar value)
1349 {
1350 AssertIsFinite(value);
1351
1352 if (value == PetscScalar())
1353 {
1354 // we have to check after using Insert/Add in any case to be
1355 // consistent with the MPI communication model, but we can save
1356 // some work if the addend is zero. However, these actions are done
1357 // in case we pass on to the other function.
1358 prepare_action(VectorOperation::add);
1359
1360 return;
1361 }
1362 else
1363 add(i, 1, &j, &value, false);
1364 }
1365
1366
1367
1368 inline void
1369 MatrixBase::add(const std::vector<size_type> &indices,
1370 const FullMatrix<PetscScalar> &values,
1371 const bool elide_zero_values)
1372 {
1373 Assert(indices.size() == values.m(),
1374 ExcDimensionMismatch(indices.size(), values.m()));
1375 Assert(values.m() == values.n(), ExcNotQuadratic());
1376
1377 for (size_type i = 0; i < indices.size(); ++i)
1378 add(indices[i],
1379 indices.size(),
1380 indices.data(),
1381 &values(i, 0),
1382 elide_zero_values);
1383 }
1384
1385
1386
1387 inline void
1388 MatrixBase::add(const std::vector<size_type> &row_indices,
1389 const std::vector<size_type> &col_indices,
1390 const FullMatrix<PetscScalar> &values,
1391 const bool elide_zero_values)
1392 {
1393 Assert(row_indices.size() == values.m(),
1394 ExcDimensionMismatch(row_indices.size(), values.m()));
1395 Assert(col_indices.size() == values.n(),
1396 ExcDimensionMismatch(col_indices.size(), values.n()));
1397
1398 for (size_type i = 0; i < row_indices.size(); ++i)
1399 add(row_indices[i],
1400 col_indices.size(),
1401 col_indices.data(),
1402 &values(i, 0),
1403 elide_zero_values);
1404 }
1405
1406
1407
1408 inline void
1409 MatrixBase::add(const size_type row,
1410 const std::vector<size_type> &col_indices,
1411 const std::vector<PetscScalar> &values,
1412 const bool elide_zero_values)
1413 {
1414 Assert(col_indices.size() == values.size(),
1415 ExcDimensionMismatch(col_indices.size(), values.size()));
1416
1417 add(row,
1418 col_indices.size(),
1419 col_indices.data(),
1420 values.data(),
1421 elide_zero_values);
1422 }
1423
1424
1425
1426 inline void
1427 MatrixBase::add(const size_type row,
1428 const size_type n_cols,
1429 const size_type *col_indices,
1430 const PetscScalar *values,
1431 const bool elide_zero_values,
1432 const bool /*col_indices_are_sorted*/)
1433 {
1434 add_or_set(VectorOperation::add,
1435 row,
1436 n_cols,
1437 col_indices,
1438 values,
1439 elide_zero_values);
1440 }
1441
1442
1443
1444 inline void
1445 MatrixBase::add_or_set(const VectorOperation::values &operation,
1446 const size_type row,
1447 const size_type n_cols,
1448 const size_type *col_indices,
1449 const PetscScalar *values,
1450 const bool elide_zero_values)
1451 {
1452 prepare_action(operation);
1453
1454 const auto petsc_row = static_cast<PetscInt>(row);
1455 AssertIntegerConversion(petsc_row, row);
1456
1457 // Use 100 entries so that we can store a row of a matrix constructed with
1458 // FESystem<3>(FE_Q<3>(2), 3, FE_Q<3>(1), 1) (i.e., a common Stokes FE,
1459 // which has 89 DoFs) with room to spare without allocating memory in the
1460 // free store.
1461 //
1462 // Setting up small_vectors isn't free so only set up column_values if we
1463 // actually use it.
1464 boost::container::small_vector<PetscInt, 100> column_indices;
1465 std::optional<boost::container::small_vector<PetscScalar, 100>>
1466 column_values;
1467
1468 const PetscScalar *values_ptr = nullptr;
1469 if (elide_zero_values == false)
1470 {
1471 column_indices.resize(n_cols);
1472
1473 for (size_type j = 0; j < n_cols; ++j)
1474 {
1475 AssertIsFinite(values[j]);
1476 column_indices[j] = static_cast<PetscInt>(col_indices[j]);
1477 AssertIntegerConversion(column_indices[j], col_indices[j]);
1478 }
1479
1480 values_ptr = values;
1481 }
1482 else
1483 {
1484 // Otherwise, extract nonzero values in each row and get the
1485 // respective index.
1486 column_values.emplace();
1487 for (size_type j = 0; j < n_cols; ++j)
1488 {
1489 const PetscScalar value = values[j];
1490 AssertIsFinite(value);
1491 if (value != PetscScalar())
1492 {
1493 column_indices.push_back(static_cast<PetscInt>(col_indices[j]));
1494 AssertIntegerConversion(column_indices.back(), col_indices[j]);
1495 column_values->push_back(value);
1496 }
1497 }
1498 values_ptr = column_values->data();
1499 }
1500
1501 const auto petsc_n_columns = static_cast<PetscInt>(column_indices.size());
1502 AssertIntegerConversion(petsc_n_columns, column_indices.size());
1503
1504 Assert(operation == VectorOperation::insert ||
1505 operation == VectorOperation::add,
1506 ExcInternalError());
1507 const PetscErrorCode ierr =
1508 MatSetValues(matrix,
1509 1,
1510 &petsc_row,
1511 petsc_n_columns,
1512 column_indices.data(),
1513 values_ptr,
1514 operation == VectorOperation::insert ? INSERT_VALUES :
1515 ADD_VALUES);
1516 AssertThrow(ierr == 0, ExcPETScError(ierr));
1517 }
1518
1519
1520
1521 inline PetscScalar
1522 MatrixBase::operator()(const size_type i, const size_type j) const
1523 {
1524 return el(i, j);
1525 }
1526
1527
1528
1529 inline MatrixBase::const_iterator
1530 MatrixBase::begin() const
1531 {
1532 Assert(
1533 (in_local_range(0) && in_local_range(m() - 1)),
1534 ExcMessage(
1535 "begin() and end() can only be called on a processor owning the entire matrix. If this is a distributed matrix, use begin(row) and end(row) instead."));
1536
1537 // find the first non-empty row in order to make sure that the returned
1538 // iterator points to something useful
1539 size_type first_nonempty_row = 0;
1540 while ((first_nonempty_row < m()) && (row_length(first_nonempty_row) == 0))
1541 ++first_nonempty_row;
1542
1543 return const_iterator(this, first_nonempty_row, 0);
1544 }
1545
1546
1547 inline MatrixBase::const_iterator
1548 MatrixBase::end() const
1549 {
1550 Assert(
1551 (in_local_range(0) && in_local_range(m() - 1)),
1552 ExcMessage(
1553 "begin() and end() can only be called on a processor owning the entire matrix. If this is a distributed matrix, use begin(row) and end(row) instead."));
1554
1555 return const_iterator(this, m(), 0);
1556 }
1557
1558
1559 inline MatrixBase::const_iterator
1560 MatrixBase::begin(const size_type r) const
1561 {
1562 Assert(in_local_range(r),
1563 ExcIndexRange(r, local_range().first, local_range().second));
1564
1565 if (row_length(r) > 0)
1566 return const_iterator(this, r, 0);
1567 else
1568 return end(r);
1569 }
1570
1571
1572 inline MatrixBase::const_iterator
1573 MatrixBase::end(const size_type r) const
1574 {
1575 Assert(in_local_range(r),
1576 ExcIndexRange(r, local_range().first, local_range().second));
1577
1578 // place the iterator on the first entry past this line, or at the
1579 // end of the matrix
1580 //
1581 // in the parallel case, we need to put it on the first entry of
1582 // the first row after the locally owned range. this of course
1583 // doesn't exist, but we can nevertheless create such an
1584 // iterator. we need to check whether 'i' is past the locally
1585 // owned range of rows first, before we ask for the length of the
1586 // row since the latter query leads to an exception in case we ask
1587 // for a row that is not locally owned
1588 for (size_type i = r + 1; i < m(); ++i)
1589 if (i == local_range().second || (row_length(i) > 0))
1590 return const_iterator(this, i, 0);
1591
1592 // if there is no such line, then take the
1593 // end iterator of the matrix
1594 // we don't allow calling end() directly for distributed matrices so we need
1595 // to copy the code without the assertion.
1596 return {this, m(), 0};
1597 }
1598
1599
1600
1601 inline bool
1602 MatrixBase::in_local_range(const size_type index) const
1603 {
1604 PetscInt petsc_begin, petsc_end;
1605
1606 const PetscErrorCode ierr =
1607 MatGetOwnershipRange(static_cast<const Mat &>(matrix),
1608 &petsc_begin,
1609 &petsc_end);
1610 AssertThrow(ierr == 0, ExcPETScError(ierr));
1611
1612 const auto begin = static_cast<size_type>(petsc_begin);
1613 AssertIntegerConversion(begin, petsc_begin);
1614 const auto end = static_cast<size_type>(petsc_end);
1615 AssertIntegerConversion(end, petsc_end);
1616
1617 return ((index >= begin) && (index < end));
1618 }
1619
1620
1621
1622 inline void
1623 MatrixBase::prepare_action(const VectorOperation::values new_action)
1624 {
1625 if (last_action == VectorOperation::unknown)
1626 last_action = new_action;
1627
1628 Assert(last_action == new_action, ExcWrongMode(last_action, new_action));
1629 }
1630
1631
1632
1633 inline void
1634 MatrixBase::assert_is_compressed()
1635 {
1636 // compress() sets the last action to none, which allows us to check if
1637 // there are pending add/insert operations:
1638 AssertThrow(last_action == VectorOperation::unknown,
1639 ExcMessage("Error: missing compress() call."));
1640 }
1641
1642
1643
1644 inline void
1645 MatrixBase::prepare_add()
1646 {
1647 prepare_action(VectorOperation::add);
1648 }
1649
1650
1651
1652 inline void
1653 MatrixBase::prepare_set()
1654 {
1655 prepare_action(VectorOperation::insert);
1656 }
1657
1658 inline MPI_Comm
1659 MatrixBase::get_mpi_communicator() const
1660 {
1661 return PetscObjectComm(reinterpret_cast<PetscObject>(matrix));
1662 }
1663
1664 # endif // DOXYGEN
1665 } // namespace PETScWrappers
1666
1667
1668 DEAL_II_NAMESPACE_CLOSE
1669
1670
1671 #else
1672
1673 // Make sure the scripts that create the C++20 module input files have
1674 // something to latch on if the preprocessor #ifdef above would
1675 // otherwise lead to an empty content of the file.
1676 DEAL_II_NAMESPACE_OPEN
1677 DEAL_II_NAMESPACE_CLOSE
1678
1679 #endif // DEAL_II_WITH_PETSC
1680
1681 #endif