Debian Codegraph @

include/deal.II/lac/block_matrix_base.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2004 - 2025 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_block_matrix_base_h
16 #define dealii_block_matrix_base_h
17
18
19 #include <deal.II/base/config.h>
20
21 #include <deal.II/base/memory_consumption.h>
22 #include <deal.II/base/mutex.h>
23 #include <deal.II/base/observer_pointer.h>
24 #include <deal.II/base/table.h>
25 #include <deal.II/base/utilities.h>
26
27 #include <deal.II/lac/block_indices.h>
28 #include <deal.II/lac/exceptions.h>
29 #include <deal.II/lac/full_matrix.h>
30 #include <deal.II/lac/matrix_iterator.h>
31 #include <deal.II/lac/vector.h>
32 #include <deal.II/lac/vector_operation.h>
33
34 #include <cmath>
35 #include <mutex>
36
37 DEAL_II_NAMESPACE_OPEN
38
39
40 // Forward declaration
41 #ifndef DOXYGEN
42 template <typename>
43 class MatrixIterator;
44 #endif
45
46
47 /**
48 * @addtogroup Matrix1
49 * @{
50 */
51
52 /**
53 * Namespace in which iterators in block matrices are implemented.
54 */
55 namespace BlockMatrixIterators
56 {
57 /**
58 * Base class for block matrix accessors, implementing the stepping through
59 * a matrix.
60 */
61 template <typename BlockMatrixType>
62 class AccessorBase
63 {
64 public:
65 /**
66 * Declare type for container size.
67 */
68 using size_type = types::global_dof_index;
69
70 /**
71 * Typedef the value type of the matrix we point into.
72 */
73 using value_type = typename BlockMatrixType::value_type;
74
75 /**
76 * Initialize data fields to default values.
77 */
78 AccessorBase();
79
80 /**
81 * Block row of the element represented by this object.
82 */
83 unsigned int
84 block_row() const;
85
86 /**
87 * Block column of the element represented by this object.
88 */
89 unsigned int
90 block_column() const;
91
92 protected:
93 /**
94 * Block row into which we presently point.
95 */
96 unsigned int row_block;
97
98 /**
99 * Block column into which we presently point.
100 */
101 unsigned int col_block;
102 };
103
104
105
106 /**
107 * Accessor classes in block matrices.
108 */
109 template <typename BlockMatrixType, bool Constness>
110 class Accessor;
111
112
113 /**
114 * Block matrix accessor for non const matrices.
115 */
116 template <typename BlockMatrixType>
117 class Accessor<BlockMatrixType, false> : public AccessorBase<BlockMatrixType>
118 {
119 public:
120 /**
121 * Declare type for container size.
122 */
123 using size_type = types::global_dof_index;
124
125 /**
126 * Type of the matrix used in this accessor.
127 */
128 using MatrixType = BlockMatrixType;
129
130 /**
131 * Typedef the value type of the matrix we point into.
132 */
133 using value_type = typename BlockMatrixType::value_type;
134
135 /**
136 * Constructor. Since we use accessors only for read access, a const
137 * matrix pointer is sufficient.
138 *
139 * Place the iterator at the beginning of the given row of the matrix, or
140 * create the end pointer if @p row equals the total number of rows in the
141 * matrix.
142 */
143 Accessor(BlockMatrixType *m, const size_type row, const size_type col);
144
145 /**
146 * Row number of the element represented by this object.
147 */
148 size_type
149 row() const;
150
151 /**
152 * Column number of the element represented by this object.
153 */
154 size_type
155 column() const;
156
157 /**
158 * Value of the entry at the current position.
159 */
160 value_type
161 value() const;
162
163 /**
164 * Set new value.
165 */
166 void
167 set_value(value_type newval) const;
168
169 protected:
170 /**
171 * The matrix accessed.
172 */
173 BlockMatrixType *matrix;
174
175 /**
176 * Iterator of the underlying matrix class.
177 */
178 typename BlockMatrixType::BlockType::iterator base_iterator;
179
180 /**
181 * Move ahead one element.
182 */
183 void
184 advance();
185
186 /**
187 * Compare this accessor with another one for equality.
188 */
189 bool
190 operator==(const Accessor &a) const;
191
192 template <typename>
193 friend class dealii::MatrixIterator;
194
195 friend class Accessor<BlockMatrixType, true>;
196 };
197
198
199
200 /**
201 * Block matrix accessor for constant matrices, implementing the stepping
202 * through a matrix.
203 */
204 template <typename BlockMatrixType>
205 class Accessor<BlockMatrixType, true> : public AccessorBase<BlockMatrixType>
206 {
207 public:
208 /**
209 * Declare type for container size.
210 */
211 using size_type = types::global_dof_index;
212
213 /**
214 * Type of the matrix used in this accessor.
215 */
216 using MatrixType = const BlockMatrixType;
217
218 /**
219 * Typedef the value type of the matrix we point into.
220 */
221 using value_type = typename BlockMatrixType::value_type;
222
223 /**
224 * Constructor. Since we use accessors only for read access, a const
225 * matrix pointer is sufficient.
226 *
227 * Place the iterator at the beginning of the given row of the matrix, or
228 * create the end pointer if @p row equals the total number of rows in the
229 * matrix.
230 */
231 Accessor(const BlockMatrixType *m,
232 const size_type row,
233 const size_type col);
234
235 /**
236 * Initialize const accessor from non const accessor.
237 */
238 Accessor(const Accessor<BlockMatrixType, false> &);
239
240 /**
241 * Row number of the element represented by this object.
242 */
243 size_type
244 row() const;
245
246 /**
247 * Column number of the element represented by this object.
248 */
249 size_type
250 column() const;
251
252 /**
253 * Value of the entry at the current position.
254 */
255 value_type
256 value() const;
257
258 protected:
259 /**
260 * The matrix accessed.
261 */
262 const BlockMatrixType *matrix;
263
264 /**
265 * Iterator of the underlying matrix class.
266 */
267 typename BlockMatrixType::BlockType::const_iterator base_iterator;
268
269 /**
270 * Move ahead one element.
271 */
272 void
273 advance();
274
275 /**
276 * Compare this accessor with another one for equality.
277 */
278 bool
279 operator==(const Accessor &a) const;
280
281 // Let the iterator class be a friend.
282 template <typename>
283 friend class dealii::MatrixIterator;
284 };
285 } // namespace BlockMatrixIterators
286
287
288
289 /**
290 * Blocked matrix class. The behavior of objects of this type is almost as
291 * for the usual matrix objects, with most of the functions being implemented
292 * in both classes. The main difference is that the matrix represented by this
293 * object is composed of an array of matrices (e.g. of type
294 * SparseMatrix<number>) and all accesses to the elements of this object are
295 * relayed to accesses of the base matrices. The actual type of the individual
296 * blocks of this matrix is the type of the template argument, and can, for
297 * example be the usual SparseMatrix or PETScWrappers::SparseMatrix.
298 *
299 * In addition to the usual matrix access and linear algebra functions, there
300 * are functions block() which allow access to the different blocks of the
301 * matrix. This may, for example, be of help when you want to implement Schur
302 * complement methods, or block preconditioners, where each block belongs to a
303 * specific component of the equation you are presently discretizing.
304 *
305 * Note that the numbers of blocks and rows are implicitly determined by the
306 * sparsity pattern objects used.
307 *
308 * Objects of this type are frequently used when a system of differential
309 * equations has solutions with variables that fall into different classes.
310 * For example, solutions of the Stokes or Navier-Stokes equations have @p dim
311 * velocity components and one pressure component. In this case, it may make
312 * sense to consider the linear system of equations as a system of 2x2 blocks,
313 * and one can construct preconditioners or solvers based on this 2x2 block
314 * structure. This class can help you in these cases, as it allows to view the
315 * matrix alternatively as one big matrix, or as a number of individual
316 * blocks.
317 *
318 *
319 * <h3>Inheriting from this class</h3>
320 *
321 * Since this class simply forwards its calls to the subobjects (if necessary
322 * after adjusting indices denoting which subobject is meant), this class is
323 * completely independent of the actual type of the subobject. The functions
324 * that set up block matrices and destroy them, however, have to be
325 * implemented in derived classes. These functions also have to fill the data
326 * members provided by this base class, as they are only used passively in
327 * this class.
328 *
329 *
330 * Most of the functions take a vector or block vector argument. These
331 * functions can, in general, only successfully be compiled if the individual
332 * blocks of this matrix implement the respective functions operating on the
333 * vector type in question. For example, if you have a block sparse matrix
334 * over deal.II SparseMatrix objects, then you will likely not be able to form
335 * the matrix-vector multiplication with a block vector over
336 * PETScWrappers::SparseMatrix objects. If you attempt anyway, you will likely
337 * get a number of compiler errors.
338 *
339 * @note Instantiations for this template are provided for <tt>@<float@> and
340 * @<double@></tt>; others can be generated in application programs (see the
341 * section on
342 * @ref Instantiations
343 * in the manual).
344 *
345 * @see
346 * @ref GlossBlockLA "Block (linear algebra)"
347 */
348 template <typename MatrixType>
349 class BlockMatrixBase : public EnableObserverPointer
350 {
351 public:
352 /**
353 * Typedef the type of the underlying matrix.
354 */
355 using BlockType = MatrixType;
356
357 /**
358 * Type of matrix entries. These are analogous to alias in the standard
359 * library containers.
360 */
361 using value_type = typename BlockType::value_type;
362 using real_type = typename numbers::NumberTraits<value_type>::real_type;
363 using pointer = value_type *;
364 using const_pointer = const value_type *;
365 using reference = value_type &;
366 using const_reference = const value_type &;
367 using size_type = types::global_dof_index;
368
369 using iterator =
370 MatrixIterator<BlockMatrixIterators::Accessor<BlockMatrixBase, false>>;
371
372 using const_iterator =
373 MatrixIterator<BlockMatrixIterators::Accessor<BlockMatrixBase, true>>;
374
375
376 /**
377 * Default constructor.
378 */
379 BlockMatrixBase() = default;
380
381 /**
382 * Destructor.
383 */
384 ~BlockMatrixBase() override;
385
386 /**
387 * Copy the matrix given as argument into the current object.
388 *
389 * Copying matrices is an expensive operation that we do not want to happen
390 * by accident through compiler generated code for <code>operator=</code>.
391 * (This would happen, for example, if one accidentally declared a function
392 * argument of the current type <i>by value</i> rather than <i>by
393 * reference</i>.) The functionality of copying matrices is implemented in
394 * this member function instead. All copy operations of objects of this type
395 * therefore require an explicit function call.
396 *
397 * The source matrix may be a matrix of arbitrary type, as long as its data
398 * type is convertible to the data type of this matrix.
399 *
400 * The function returns a reference to <tt>this</tt>.
401 */
402 template <typename BlockMatrixType>
403 BlockMatrixBase &
404 copy_from(const BlockMatrixType &source);
405
406 /**
407 * Access the block with the given coordinates.
408 */
409 BlockType &
410 block(const unsigned int row, const unsigned int column);
411
412
413 /**
414 * Access the block with the given coordinates. Version for constant
415 * objects.
416 */
417 const BlockType &
418 block(const unsigned int row, const unsigned int column) const;
419
420 /**
421 * Return the dimension of the codomain (or range) space. Note that the
422 * matrix is of dimension $m \times n$.
423 */
424 size_type
425 m() const;
426
427 /**
428 * Return the dimension of the domain space. Note that the matrix is of
429 * dimension $m \times n$.
430 */
431 size_type
432 n() const;
433
434
435 /**
436 * Return the number of blocks in a column. Returns zero if no sparsity
437 * pattern is presently associated to this matrix.
438 */
439 unsigned int
440 n_block_rows() const;
441
442 /**
443 * Return the number of blocks in a row. Returns zero if no sparsity pattern
444 * is presently associated to this matrix.
445 */
446 unsigned int
447 n_block_cols() const;
448
449 /**
450 * Set the element <tt>(i,j)</tt> to <tt>value</tt>. Throws an error if the
451 * entry does not exist or if <tt>value</tt> is not a finite number. Still,
452 * it is allowed to store zero values in non-existent fields.
453 */
454 void
455 set(const size_type i, const size_type j, const value_type value);
456
457 /**
458 * Set all elements given in a FullMatrix into the sparse matrix locations
459 * given by <tt>indices</tt>. In other words, this function writes the
460 * elements in <tt>full_matrix</tt> into the calling matrix, using the
461 * local-to-global indexing specified by <tt>indices</tt> for both the rows
462 * and the columns of the matrix. This function assumes a quadratic sparse
463 * matrix and a quadratic full_matrix, the usual situation in FE
464 * calculations.
465 *
466 * The optional parameter <tt>elide_zero_values</tt> can be used to specify
467 * whether zero values should be set anyway or they should be filtered away
468 * (and not change the previous content in the respective element if it
469 * exists). The default value is <tt>false</tt>, i.e., even zero values are
470 * treated.
471 */
472 template <typename number>
473 void
474 set(const std::vector<size_type> &indices,
475 const FullMatrix<number> &full_matrix,
476 const bool elide_zero_values = false);
477
478 /**
479 * Same function as before, but now including the possibility to use
480 * rectangular full_matrices and different local-to-global indexing on rows
481 * and columns, respectively.
482 */
483 template <typename number>
484 void
485 set(const std::vector<size_type> &row_indices,
486 const std::vector<size_type> &col_indices,
487 const FullMatrix<number> &full_matrix,
488 const bool elide_zero_values = false);
489
490 /**
491 * Set several elements in the specified row of the matrix with column
492 * indices as given by <tt>col_indices</tt> to the respective value.
493 *
494 * The optional parameter <tt>elide_zero_values</tt> can be used to specify
495 * whether zero values should be set anyway or they should be filtered away
496 * (and not change the previous content in the respective element if it
497 * exists). The default value is <tt>false</tt>, i.e., even zero values are
498 * treated.
499 */
500 template <typename number>
501 void
502 set(const size_type row,
503 const std::vector<size_type> &col_indices,
504 const std::vector<number> &values,
505 const bool elide_zero_values = false);
506
507 /**
508 * Set several elements to values given by <tt>values</tt> in a given row in
509 * columns given by col_indices into the sparse matrix.
510 *
511 * The optional parameter <tt>elide_zero_values</tt> can be used to specify
512 * whether zero values should be inserted anyway or they should be filtered
513 * away. The default value is <tt>false</tt>, i.e., even zero values are
514 * inserted/replaced.
515 */
516 template <typename number>
517 void
518 set(const size_type row,
519 const size_type n_cols,
520 const size_type *col_indices,
521 const number *values,
522 const bool elide_zero_values = false);
523
524 /**
525 * Add <tt>value</tt> to the element (<i>i,j</i>). Throws an error if the
526 * entry does not exist or if <tt>value</tt> is not a finite number. Still,
527 * it is allowed to store zero values in non-existent fields.
528 */
529 void
530 add(const size_type i, const size_type j, const value_type value);
531
532 /**
533 * Add all elements given in a FullMatrix<double> into sparse matrix
534 * locations given by <tt>indices</tt>. In other words, this function adds
535 * the elements in <tt>full_matrix</tt> to the respective entries in calling
536 * matrix, using the local-to-global indexing specified by <tt>indices</tt>
537 * for both the rows and the columns of the matrix. This function assumes a
538 * quadratic sparse matrix and a quadratic full_matrix, the usual situation
539 * in FE calculations.
540 *
541 * The optional parameter <tt>elide_zero_values</tt> can be used to specify
542 * whether zero values should be added anyway or these should be filtered
543 * away and only non-zero data is added. The default value is <tt>true</tt>,
544 * i.e., zero values won't be added into the matrix.
545 */
546 template <typename number>
547 void
548 add(const std::vector<size_type> &indices,
549 const FullMatrix<number> &full_matrix,
550 const bool elide_zero_values = true);
551
552 /**
553 * Same function as before, but now including the possibility to use
554 * rectangular full_matrices and different local-to-global indexing on rows
555 * and columns, respectively.
556 */
557 template <typename number>
558 void
559 add(const std::vector<size_type> &row_indices,
560 const std::vector<size_type> &col_indices,
561 const FullMatrix<number> &full_matrix,
562 const bool elide_zero_values = true);
563
564 /**
565 * Set several elements in the specified row of the matrix with column
566 * indices as given by <tt>col_indices</tt> to the respective value.
567 *
568 * The optional parameter <tt>elide_zero_values</tt> can be used to specify
569 * whether zero values should be added anyway or these should be filtered
570 * away and only non-zero data is added. The default value is <tt>true</tt>,
571 * i.e., zero values won't be added into the matrix.
572 */
573 template <typename number>
574 void
575 add(const size_type row,
576 const std::vector<size_type> &col_indices,
577 const std::vector<number> &values,
578 const bool elide_zero_values = true);
579
580 /**
581 * Add an array of values given by <tt>values</tt> in the given global
582 * matrix row at columns specified by col_indices in the sparse matrix.
583 *
584 * The optional parameter <tt>elide_zero_values</tt> can be used to specify
585 * whether zero values should be added anyway or these should be filtered
586 * away and only non-zero data is added. The default value is <tt>true</tt>,
587 * i.e., zero values won't be added into the matrix.
588 */
589 template <typename number>
590 void
591 add(const size_type row,
592 const size_type n_cols,
593 const size_type *col_indices,
594 const number *values,
595 const bool elide_zero_values = true,
596 const bool col_indices_are_sorted = false);
597
598 /**
599 * Add <tt>matrix</tt> scaled by <tt>factor</tt> to this matrix, i.e. the
600 * matrix <tt>factor*matrix</tt> is added to <tt>this</tt>. If the sparsity
601 * pattern of the calling matrix does not contain all the elements in the
602 * sparsity pattern of the input matrix, this function will throw an
603 * exception.
604 *
605 * Depending on MatrixType, however, additional restrictions might arise.
606 * Some sparse matrix formats require <tt>matrix</tt> to be based on the
607 * same sparsity pattern as the calling matrix.
608 */
609 void
610 add(const value_type factor, const BlockMatrixBase<MatrixType> &matrix);
611
612 /**
613 * Return the value of the entry (i,j). This may be an expensive operation
614 * and you should always take care where to call this function. In order to
615 * avoid abuse, this function throws an exception if the wanted element does
616 * not exist in the matrix.
617 */
618 value_type
619 operator()(const size_type i, const size_type j) const;
620
621 /**
622 * This function is mostly like operator()() in that it returns the value of
623 * the matrix entry <tt>(i,j)</tt>. The only difference is that if this
624 * entry does not exist in the sparsity pattern, then instead of raising an
625 * exception, zero is returned. While this may be convenient in some cases,
626 * note that it is simple to write algorithms that are slow compared to an
627 * optimal solution, since the sparsity of the matrix is not used.
628 */
629 value_type
630 el(const size_type i, const size_type j) const;
631
632 /**
633 * Return the main diagonal element in the <i>i</i>th row. This function
634 * throws an error if the matrix is not quadratic and also if the diagonal
635 * blocks of the matrix are not quadratic.
636 *
637 * This function is considerably faster than the operator()(), since for
638 * quadratic matrices, the diagonal entry may be the first to be stored in
639 * each row and access therefore does not involve searching for the right
640 * column number.
641 */
642 value_type
643 diag_element(const size_type i) const;
644
645 /**
646 * Call the compress() function on all the subblocks of the matrix.
647 *
648 *
649 * See
650 * @ref GlossCompress "Compressing distributed objects"
651 * for more information.
652 */
653 void
654 compress(VectorOperation::values operation);
655
656 /**
657 * Multiply the entire matrix by a fixed factor.
658 */
659 BlockMatrixBase &
660 operator*=(const value_type factor);
661
662 /**
663 * Divide the entire matrix by a fixed factor.
664 */
665 BlockMatrixBase &
666 operator/=(const value_type factor);
667
668 /**
669 * Adding Matrix-vector multiplication. Add $M*src$ on $dst$ with $M$ being
670 * this matrix.
671 */
672 template <typename BlockVectorType>
673 void
674 vmult_add(BlockVectorType &dst, const BlockVectorType &src) const;
675
676 /**
677 * Adding Matrix-vector multiplication. Add <i>M<sup>T</sup>src</i> to
678 * <i>dst</i> with <i>M</i> being this matrix. This function does the same
679 * as vmult_add() but takes the transposed matrix.
680 */
681 template <typename BlockVectorType>
682 void
683 Tvmult_add(BlockVectorType &dst, const BlockVectorType &src) const;
684
685 /**
686 * Return the norm of the vector <i>v</i> with respect to the norm induced
687 * by this matrix, i.e. <i>v<sup>T</sup>Mv)</i>. This is useful, e.g. in the
688 * finite element context, where the <i>L<sup>T</sup></i>-norm of a function
689 * equals the matrix norm with respect to the @ref GlossMassMatrix "mass matrix" of the vector
690 * representing the nodal values of the finite element function. Note that
691 * even though the function's name might suggest something different, for
692 * historic reasons not the norm but its square is returned, as defined
693 * above by the scalar product.
694 *
695 * Obviously, the matrix needs to be square for this operation.
696 */
697 template <typename BlockVectorType>
698 value_type
699 matrix_norm_square(const BlockVectorType &v) const;
700
701 /**
702 * Return the frobenius norm of the matrix, i.e. the square root of the sum
703 * of squares of all entries in the matrix.
704 */
705 real_type
706 frobenius_norm() const;
707
708 /**
709 * Compute the matrix scalar product $\left(u,Mv\right)$.
710 */
711 template <typename BlockVectorType>
712 value_type
713 matrix_scalar_product(const BlockVectorType &u,
714 const BlockVectorType &v) const;
715
716 /**
717 * Compute the residual <i>r=b-Ax</i>. Write the residual into <tt>dst</tt>.
718 */
719 template <typename BlockVectorType>
720 value_type
721 residual(BlockVectorType &dst,
722 const BlockVectorType &x,
723 const BlockVectorType &b) const;
724
725 /**
726 * Print the matrix to the given stream, using the format <tt>(line,col)
727 * value</tt>, i.e. one nonzero entry of the matrix per line. The optional
728 * flag outputs the sparsity pattern in a different style according to the
729 * underlying sparse matrix type.
730 */
731 void
732 print(std::ostream &out, const bool alternative_output = false) const;
733
734 /**
735 * Iterator starting at the first entry.
736 */
737 iterator
738 begin();
739
740 /**
741 * Final iterator.
742 */
743 iterator
744 end();
745
746 /**
747 * Iterator starting at the first entry of row <tt>r</tt>.
748 */
749 iterator
750 begin(const size_type r);
751
752 /**
753 * Final iterator of row <tt>r</tt>.
754 */
755 iterator
756 end(const size_type r);
757 /**
758 * Iterator starting at the first entry.
759 */
760 const_iterator
761 begin() const;
762
763 /**
764 * Final iterator.
765 */
766 const_iterator
767 end() const;
768
769 /**
770 * Iterator starting at the first entry of row <tt>r</tt>.
771 */
772 const_iterator
773 begin(const size_type r) const;
774
775 /**
776 * Final iterator of row <tt>r</tt>.
777 */
778 const_iterator
779 end(const size_type r) const;
780
781 /**
782 * Return a reference to the underlying BlockIndices data of the rows.
783 */
784 const BlockIndices &
785 get_row_indices() const;
786
787 /**
788 * Return a reference to the underlying BlockIndices data of the columns.
789 */
790 const BlockIndices &
791 get_column_indices() const;
792
793 /**
794 * Determine an estimate for the memory consumption (in bytes) of this
795 * object. Note that only the memory reserved on the current processor is
796 * returned in case this is called in an MPI-based program.
797 */
798 std::size_t
799 memory_consumption() const;
800
801 /**
802 * @addtogroup Exceptions
803 * @{
804 */
805
806 /**
807 * Exception
808 */
809 DeclException4(ExcIncompatibleRowNumbers,
810 int,
811 int,
812 int,
813 int,
814 << "The blocks [" << arg1 << ',' << arg2 << "] and [" << arg3
815 << ',' << arg4 << "] have differing row numbers.");
816 /**
817 * Exception
818 */
819 DeclException4(ExcIncompatibleColNumbers,
820 int,
821 int,
822 int,
823 int,
824 << "The blocks [" << arg1 << ',' << arg2 << "] and [" << arg3
825 << ',' << arg4 << "] have differing column numbers.");
826 /** @} */
827 protected:
828 /**
829 * Release all memory and return to a state just like after having called
830 * the default constructor. It also forgets the sparsity pattern it was
831 * previously tied to.
832 *
833 * This calls clear for all sub-matrices and then resets this object to have
834 * no blocks at all.
835 *
836 * This function is protected since it may be necessary to release
837 * additional structures. A derived class can make it public again, if it is
838 * sufficient.
839 */
840 void
841 clear();
842
843 /**
844 * Index arrays for rows and columns.
845 */
846 BlockIndices row_block_indices;
847 BlockIndices column_block_indices;
848
849 /**
850 * Array of sub-matrices.
851 */
852 Table<2, ObserverPointer<BlockType, BlockMatrixBase<MatrixType>>> sub_objects;
853
854 /**
855 * This function collects the sizes of the sub-objects and stores them in
856 * internal arrays, in order to be able to relay global indices into the
857 * matrix to indices into the subobjects. You *must* call this function each
858 * time after you have changed the size of the sub-objects.
859 *
860 * Derived classes should call this function whenever the size of the
861 * sub-objects has changed and the @p X_block_indices arrays need to be updated.
862 *
863 * Note that this function is not public since not all derived classes need
864 * to export its interface. For example, for the usual deal.II SparseMatrix
865 * class, the sizes are implicitly determined whenever reinit() is called,
866 * and individual blocks cannot be resized. For that class, this function
867 * therefore does not have to be public. On the other hand, for the PETSc
868 * classes, there is no associated sparsity pattern object that determines
869 * the block sizes, and for these the function needs to be publicly
870 * available. These classes therefore export this function.
871 */
872 void
873 collect_sizes();
874
875 /**
876 * Matrix-vector multiplication: let $dst = M*src$ with $M$ being this
877 * matrix.
878 *
879 * Due to problems with deriving template arguments between the block and
880 * non-block versions of the vmult/Tvmult functions, the actual functions
881 * are implemented in derived classes, with implementations forwarding the
882 * calls to the implementations provided here under a unique name for which
883 * template arguments can be derived by the compiler.
884 */
885 template <typename BlockVectorType>
886 void
887 vmult_block_block(BlockVectorType &dst, const BlockVectorType &src) const;
888
889 /**
890 * Matrix-vector multiplication. Just like the previous function, but only
891 * applicable if the matrix has only one block column.
892 *
893 * Due to problems with deriving template arguments between the block and
894 * non-block versions of the vmult/Tvmult functions, the actual functions
895 * are implemented in derived classes, with implementations forwarding the
896 * calls to the implementations provided here under a unique name for which
897 * template arguments can be derived by the compiler.
898 */
899 template <typename BlockVectorType, typename VectorType>
900 void
901 vmult_block_nonblock(BlockVectorType &dst, const VectorType &src) const;
902
903 /**
904 * Matrix-vector multiplication. Just like the previous function, but only
905 * applicable if the matrix has only one block row.
906 *
907 * Due to problems with deriving template arguments between the block and
908 * non-block versions of the vmult/Tvmult functions, the actual functions
909 * are implemented in derived classes, with implementations forwarding the
910 * calls to the implementations provided here under a unique name for which
911 * template arguments can be derived by the compiler.
912 */
913 template <typename BlockVectorType, typename VectorType>
914 void
915 vmult_nonblock_block(VectorType &dst, const BlockVectorType &src) const;
916
917 /**
918 * Matrix-vector multiplication. Just like the previous function, but only
919 * applicable if the matrix has only one block.
920 *
921 * Due to problems with deriving template arguments between the block and
922 * non-block versions of the vmult/Tvmult functions, the actual functions
923 * are implemented in derived classes, with implementations forwarding the
924 * calls to the implementations provided here under a unique name for which
925 * template arguments can be derived by the compiler.
926 */
927 template <typename VectorType>
928 void
929 vmult_nonblock_nonblock(VectorType &dst, const VectorType &src) const;
930
931 /**
932 * Matrix-vector multiplication: let $dst = M^T*src$ with $M$ being this
933 * matrix. This function does the same as vmult() but takes the transposed
934 * matrix.
935 *
936 * Due to problems with deriving template arguments between the block and
937 * non-block versions of the vmult/Tvmult functions, the actual functions
938 * are implemented in derived classes, with implementations forwarding the
939 * calls to the implementations provided here under a unique name for which
940 * template arguments can be derived by the compiler.
941 */
942 template <typename BlockVectorType>
943 void
944 Tvmult_block_block(BlockVectorType &dst, const BlockVectorType &src) const;
945
946 /**
947 * Matrix-vector multiplication. Just like the previous function, but only
948 * applicable if the matrix has only one block row.
949 *
950 * Due to problems with deriving template arguments between the block and
951 * non-block versions of the vmult/Tvmult functions, the actual functions
952 * are implemented in derived classes, with implementations forwarding the
953 * calls to the implementations provided here under a unique name for which
954 * template arguments can be derived by the compiler.
955 */
956 template <typename BlockVectorType, typename VectorType>
957 void
958 Tvmult_block_nonblock(BlockVectorType &dst, const VectorType &src) const;
959
960 /**
961 * Matrix-vector multiplication. Just like the previous function, but only
962 * applicable if the matrix has only one block column.
963 *
964 * Due to problems with deriving template arguments between the block and
965 * non-block versions of the vmult/Tvmult functions, the actual functions
966 * are implemented in derived classes, with implementations forwarding the
967 * calls to the implementations provided here under a unique name for which
968 * template arguments can be derived by the compiler.
969 */
970 template <typename BlockVectorType, typename VectorType>
971 void
972 Tvmult_nonblock_block(VectorType &dst, const BlockVectorType &src) const;
973
974 /**
975 * Matrix-vector multiplication. Just like the previous function, but only
976 * applicable if the matrix has only one block.
977 *
978 * Due to problems with deriving template arguments between the block and
979 * non-block versions of the vmult/Tvmult functions, the actual functions
980 * are implemented in derived classes, with implementations forwarding the
981 * calls to the implementations provided here under a unique name for which
982 * template arguments can be derived by the compiler.
983 */
984 template <typename VectorType>
985 void
986 Tvmult_nonblock_nonblock(VectorType &dst, const VectorType &src) const;
987
988
989 protected:
990 /**
991 * Some matrix types, in particular PETSc, need to synchronize set and add
992 * operations. This has to be done for all matrices in the BlockMatrix. This
993 * routine prepares adding of elements by notifying all blocks. Called by
994 * all internal routines before adding elements.
995 */
996 void
997 prepare_add_operation();
998
999 /**
1000 * Notifies all blocks to let them prepare for setting elements, see
1001 * prepare_add_operation().
1002 */
1003 void
1004 prepare_set_operation();
1005
1006
1007 private:
1008 /**
1009 * A structure containing some fields used by the set() and add() functions
1010 * that is used to pre-sort the input fields. Since one can reasonably
1011 * expect to call set() and add() from multiple threads at once as long as
1012 * the matrix indices that are touched are disjoint, these temporary data
1013 * fields need to be guarded by a mutex; the structure therefore contains
1014 * such a mutex as a member variable.
1015 */
1016 struct TemporaryData
1017 {
1018 /**
1019 * Temporary vector for counting the elements written into the individual
1020 * blocks when doing a collective add or set.
1021 */
1022 std::vector<size_type> counter_within_block;
1023
1024 /**
1025 * Temporary vector for column indices on each block when writing local to
1026 * global data on each sparse matrix.
1027 */
1028 std::vector<std::vector<size_type>> column_indices;
1029
1030 /**
1031 * Temporary vector for storing the local values (they need to be
1032 * reordered when writing local to global).
1033 */
1034 std::vector<std::vector<value_type>> column_values;
1035
1036 /**
1037 * A mutex variable used to guard access to the member variables of this
1038 * structure;
1039 */
1040 Threads::Mutex mutex;
1041
1042 /**
1043 * Copy operator. This is needed because the default copy operator of this
1044 * class is deleted (since std::mutex is not copyable) and hence the
1045 * default copy operator of the enclosing class is also deleted.
1046 *
1047 * The implementation here simply does nothing -- TemporaryData objects
1048 * are just scratch objects that are resized at the beginning of their
1049 * use, so there is no point actually copying anything.
1050 */
1051 TemporaryData &
1052 operator=(const TemporaryData &)
1053 {
1054 return *this;
1055 }
1056 };
1057
1058 /**
1059 * A set of scratch arrays that can be used by the add() and set() functions
1060 * that take pointers to data to pre-sort indices before use. Access from
1061 * multiple threads is synchronized via the mutex variable that is part of
1062 * the structure.
1063 */
1064 TemporaryData temporary_data;
1065
1066 // Make the iterator class a friend. We have to work around a compiler bug
1067 // here again.
1068 template <typename, bool>
1069 friend class BlockMatrixIterators::Accessor;
1070
1071 template <typename>
1072 friend class MatrixIterator;
1073 };
1074
1075
1076 /** @} */
1077
1078 #ifndef DOXYGEN
1079 /* ------------------------- Template functions ---------------------- */
1080
1081
1082 namespace BlockMatrixIterators
1083 {
1084 template <typename BlockMatrixType>
1085 inline AccessorBase<BlockMatrixType>::AccessorBase()
1086 : row_block(0)
1087 , col_block(0)
1088 {}
1089
1090
1091 template <typename BlockMatrixType>
1092 inline unsigned int
1093 AccessorBase<BlockMatrixType>::block_row() const
1094 {
1095 Assert(row_block != numbers::invalid_unsigned_int, ExcIteratorPastEnd());
1096
1097 return row_block;
1098 }
1099
1100
1101 template <typename BlockMatrixType>
1102 inline unsigned int
1103 AccessorBase<BlockMatrixType>::block_column() const
1104 {
1105 Assert(col_block != numbers::invalid_unsigned_int, ExcIteratorPastEnd());
1106
1107 return col_block;
1108 }
1109
1110
1111 template <typename BlockMatrixType>
1112 inline Accessor<BlockMatrixType, true>::Accessor(
1113 const BlockMatrixType *matrix,
1114 const size_type row,
1115 const size_type col)
1116 : matrix(matrix)
1117 , base_iterator(matrix->block(0, 0).begin())
1118 {
1119 Assert(col == 0, ExcNotImplemented());
1120
1121 // check if this is a regular row or
1122 // the end of the matrix
1123 if (row < matrix->m())
1124 {
1125 const std::pair<unsigned int, size_type> indices =
1126 matrix->row_block_indices.global_to_local(row);
1127
1128 // find the first block that does
1129 // have an entry in this row
1130 for (unsigned int bc = 0; bc < matrix->n_block_cols(); ++bc)
1131 {
1132 base_iterator =
1133 matrix->block(indices.first, bc).begin(indices.second);
1134 if (base_iterator !=
1135 matrix->block(indices.first, bc).end(indices.second))
1136 {
1137 this->row_block = indices.first;
1138 this->col_block = bc;
1139 return;
1140 }
1141 }
1142
1143 // hm, there is no block that has
1144 // an entry in this column. we need
1145 // to take the next entry then,
1146 // which may be the first entry of
1147 // the next row, or recursively the
1148 // next row, or so on
1149 *this = Accessor(matrix, row + 1, 0);
1150 }
1151 else
1152 {
1153 // we were asked to create the end
1154 // iterator for this matrix
1155 this->row_block = numbers::invalid_unsigned_int;
1156 this->col_block = numbers::invalid_unsigned_int;
1157 }
1158 }
1159
1160
1161 // template <typename BlockMatrixType>
1162 // inline
1163 // Accessor<BlockMatrixType, true>::Accessor (const
1164 // Accessor<BlockMatrixType, true>& other)
1165 // :
1166 // matrix(other.matrix),
1167 // base_iterator(other.base_iterator)
1168 // {
1169 // this->row_block = other.row_block;
1170 // this->col_block = other.col_block;
1171 // }
1172
1173
1174 template <typename BlockMatrixType>
1175 inline Accessor<BlockMatrixType, true>::Accessor(
1176 const Accessor<BlockMatrixType, false> &other)
1177 : matrix(other.matrix)
1178 , base_iterator(other.base_iterator)
1179 {
1180 this->row_block = other.row_block;
1181 this->col_block = other.col_block;
1182 }
1183
1184
1185 template <typename BlockMatrixType>
1186 inline typename Accessor<BlockMatrixType, true>::size_type
1187 Accessor<BlockMatrixType, true>::row() const
1188 {
1189 Assert(this->row_block != numbers::invalid_unsigned_int,
1190 ExcIteratorPastEnd());
1191
1192 return (matrix->row_block_indices.local_to_global(this->row_block, 0) +
1193 base_iterator->row());
1194 }
1195
1196
1197 template <typename BlockMatrixType>
1198 inline typename Accessor<BlockMatrixType, true>::size_type
1199 Accessor<BlockMatrixType, true>::column() const
1200 {
1201 Assert(this->col_block != numbers::invalid_unsigned_int,
1202 ExcIteratorPastEnd());
1203
1204 return (matrix->column_block_indices.local_to_global(this->col_block, 0) +
1205 base_iterator->column());
1206 }
1207
1208
1209 template <typename BlockMatrixType>
1210 inline typename Accessor<BlockMatrixType, true>::value_type
1211 Accessor<BlockMatrixType, true>::value() const
1212 {
1213 Assert(this->row_block != numbers::invalid_unsigned_int,
1214 ExcIteratorPastEnd());
1215 Assert(this->col_block != numbers::invalid_unsigned_int,
1216 ExcIteratorPastEnd());
1217
1218 return base_iterator->value();
1219 }
1220
1221
1222
1223 template <typename BlockMatrixType>
1224 inline void
1225 Accessor<BlockMatrixType, true>::advance()
1226 {
1227 Assert(this->row_block != numbers::invalid_unsigned_int,
1228 ExcIteratorPastEnd());
1229 Assert(this->col_block != numbers::invalid_unsigned_int,
1230 ExcIteratorPastEnd());
1231
1232 // Remember current row inside block
1233 size_type local_row = base_iterator->row();
1234
1235 // Advance one element inside the
1236 // current block
1237 ++base_iterator;
1238
1239 // while we hit the end of the row of a
1240 // block (which may happen multiple
1241 // times if rows inside a block are
1242 // empty), we have to jump to the next
1243 // block and take the
1244 while (base_iterator ==
1245 matrix->block(this->row_block, this->col_block).end(local_row))
1246 {
1247 // jump to next block in this block
1248 // row, if possible, otherwise go
1249 // to next row
1250 if (this->col_block < matrix->n_block_cols() - 1)
1251 {
1252 ++this->col_block;
1253 base_iterator =
1254 matrix->block(this->row_block, this->col_block).begin(local_row);
1255 }
1256 else
1257 {
1258 // jump back to next row in
1259 // first block column
1260 this->col_block = 0;
1261 ++local_row;
1262
1263 // see if this has brought us
1264 // past the number of rows in
1265 // this block. if so see
1266 // whether we've just fallen
1267 // off the end of the whole
1268 // matrix
1269 if (local_row ==
1270 matrix->block(this->row_block, this->col_block).m())
1271 {
1272 local_row = 0;
1273 ++this->row_block;
1274 if (this->row_block == matrix->n_block_rows())
1275 {
1276 this->row_block = numbers::invalid_unsigned_int;
1277 this->col_block = numbers::invalid_unsigned_int;
1278 return;
1279 }
1280 }
1281
1282 base_iterator =
1283 matrix->block(this->row_block, this->col_block).begin(local_row);
1284 }
1285 }
1286 }
1287
1288
1289 template <typename BlockMatrixType>
1290 inline bool
1291 Accessor<BlockMatrixType, true>::operator==(const Accessor &a) const
1292 {
1293 if (matrix != a.matrix)
1294 return false;
1295
1296 if (this->row_block == a.row_block && this->col_block == a.col_block)
1297 // end iterators do not necessarily
1298 // have to have the same
1299 // base_iterator representation, but
1300 // valid iterators have to
1301 return (((this->row_block == numbers::invalid_unsigned_int) &&
1302 (this->col_block == numbers::invalid_unsigned_int)) ||
1303 (base_iterator == a.base_iterator));
1304
1305 return false;
1306 }
1307
1308 //----------------------------------------------------------------------//
1309
1310
1311 template <typename BlockMatrixType>
1312 inline Accessor<BlockMatrixType, false>::Accessor(BlockMatrixType *matrix,
1313 const size_type row,
1314 const size_type col)
1315 : matrix(matrix)
1316 , base_iterator(matrix->block(0, 0).begin())
1317 {
1318 Assert(col == 0, ExcNotImplemented());
1319 // check if this is a regular row or
1320 // the end of the matrix
1321 if (row < matrix->m())
1322 {
1323 const std::pair<unsigned int, size_type> indices =
1324 matrix->row_block_indices.global_to_local(row);
1325
1326 // find the first block that does
1327 // have an entry in this row
1328 for (size_type bc = 0; bc < matrix->n_block_cols(); ++bc)
1329 {
1330 base_iterator =
1331 matrix->block(indices.first, bc).begin(indices.second);
1332 if (base_iterator !=
1333 matrix->block(indices.first, bc).end(indices.second))
1334 {
1335 this->row_block = indices.first;
1336 this->col_block = bc;
1337 return;
1338 }
1339 }
1340
1341 // hm, there is no block that has
1342 // an entry in this column. we need
1343 // to take the next entry then,
1344 // which may be the first entry of
1345 // the next row, or recursively the
1346 // next row, or so on
1347 *this = Accessor(matrix, row + 1, 0);
1348 }
1349 else
1350 {
1351 // we were asked to create the end
1352 // iterator for this matrix
1353 this->row_block = numbers::invalid_size_type;
1354 this->col_block = numbers::invalid_size_type;
1355 }
1356 }
1357
1358
1359 template <typename BlockMatrixType>
1360 inline typename Accessor<BlockMatrixType, false>::size_type
1361 Accessor<BlockMatrixType, false>::row() const
1362 {
1363 Assert(this->row_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1364
1365 return (matrix->row_block_indices.local_to_global(this->row_block, 0) +
1366 base_iterator->row());
1367 }
1368
1369
1370 template <typename BlockMatrixType>
1371 inline typename Accessor<BlockMatrixType, false>::size_type
1372 Accessor<BlockMatrixType, false>::column() const
1373 {
1374 Assert(this->col_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1375
1376 return (matrix->column_block_indices.local_to_global(this->col_block, 0) +
1377 base_iterator->column());
1378 }
1379
1380
1381 template <typename BlockMatrixType>
1382 inline typename Accessor<BlockMatrixType, false>::value_type
1383 Accessor<BlockMatrixType, false>::value() const
1384 {
1385 Assert(this->row_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1386 Assert(this->col_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1387
1388 return base_iterator->value();
1389 }
1390
1391
1392
1393 template <typename BlockMatrixType>
1394 inline void
1395 Accessor<BlockMatrixType, false>::set_value(
1396 typename Accessor<BlockMatrixType, false>::value_type newval) const
1397 {
1398 Assert(this->row_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1399 Assert(this->col_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1400
1401 base_iterator->value() = newval;
1402 }
1403
1404
1405
1406 template <typename BlockMatrixType>
1407 inline void
1408 Accessor<BlockMatrixType, false>::advance()
1409 {
1410 Assert(this->row_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1411 Assert(this->col_block != numbers::invalid_size_type, ExcIteratorPastEnd());
1412
1413 // Remember current row inside block
1414 size_type local_row = base_iterator->row();
1415
1416 // Advance one element inside the
1417 // current block
1418 ++base_iterator;
1419
1420 // while we hit the end of the row of a
1421 // block (which may happen multiple
1422 // times if rows inside a block are
1423 // empty), we have to jump to the next
1424 // block and take the
1425 while (base_iterator ==
1426 matrix->block(this->row_block, this->col_block).end(local_row))
1427 {
1428 // jump to next block in this block
1429 // row, if possible, otherwise go
1430 // to next row
1431 if (this->col_block < matrix->n_block_cols() - 1)
1432 {
1433 ++this->col_block;
1434 base_iterator =
1435 matrix->block(this->row_block, this->col_block).begin(local_row);
1436 }
1437 else
1438 {
1439 // jump back to next row in
1440 // first block column
1441 this->col_block = 0;
1442 ++local_row;
1443
1444 // see if this has brought us
1445 // past the number of rows in
1446 // this block. if so see
1447 // whether we've just fallen
1448 // off the end of the whole
1449 // matrix
1450 if (local_row ==
1451 matrix->block(this->row_block, this->col_block).m())
1452 {
1453 local_row = 0;
1454 ++this->row_block;
1455 if (this->row_block == matrix->n_block_rows())
1456 {
1457 this->row_block = numbers::invalid_size_type;
1458 this->col_block = numbers::invalid_size_type;
1459 return;
1460 }
1461 }
1462
1463 base_iterator =
1464 matrix->block(this->row_block, this->col_block).begin(local_row);
1465 }
1466 }
1467 }
1468
1469
1470
1471 template <typename BlockMatrixType>
1472 inline bool
1473 Accessor<BlockMatrixType, false>::operator==(const Accessor &a) const
1474 {
1475 if (matrix != a.matrix)
1476 return false;
1477
1478 if (this->row_block == a.row_block && this->col_block == a.col_block)
1479 // end iterators do not necessarily
1480 // have to have the same
1481 // base_iterator representation, but
1482 // valid iterators have to
1483 return (((this->row_block == numbers::invalid_size_type) &&
1484 (this->col_block == numbers::invalid_size_type)) ||
1485 (base_iterator == a.base_iterator));
1486
1487 return false;
1488 }
1489 } // namespace BlockMatrixIterators
1490
1491
1492 //---------------------------------------------------------------------------
1493
1494 template <typename MatrixType>
1495 inline BlockMatrixBase<MatrixType>::~BlockMatrixBase()
1496 {
1497 try
1498 {
1499 clear();
1500 }
1501 catch (...)
1502 {}
1503 }
1504
1505
1506 template <typename MatrixType>
1507 template <typename BlockMatrixType>
1508 inline BlockMatrixBase<MatrixType> &
1509 BlockMatrixBase<MatrixType>::copy_from(const BlockMatrixType &source)
1510 {
1511 for (unsigned int r = 0; r < n_block_rows(); ++r)
1512 for (unsigned int c = 0; c < n_block_cols(); ++c)
1513 block(r, c).copy_from(source.block(r, c));
1514
1515 return *this;
1516 }
1517
1518
1519 template <typename MatrixType>
1520 std::size_t
1521 BlockMatrixBase<MatrixType>::memory_consumption() const
1522 {
1523 std::size_t mem =
1524 MemoryConsumption::memory_consumption(row_block_indices) +
1525 MemoryConsumption::memory_consumption(column_block_indices) +
1526 MemoryConsumption::memory_consumption(sub_objects) +
1527 MemoryConsumption::memory_consumption(temporary_data.counter_within_block) +
1528 MemoryConsumption::memory_consumption(temporary_data.column_indices) +
1529 MemoryConsumption::memory_consumption(temporary_data.column_values) +
1530 sizeof(temporary_data.mutex);
1531
1532 for (unsigned int r = 0; r < n_block_rows(); ++r)
1533 for (unsigned int c = 0; c < n_block_cols(); ++c)
1534 {
1535 MatrixType *p = this->sub_objects[r][c];
1536 mem += MemoryConsumption::memory_consumption(*p);
1537 }
1538
1539 return mem;
1540 }
1541
1542
1543
1544 template <typename MatrixType>
1545 inline void
1546 BlockMatrixBase<MatrixType>::clear()
1547 {
1548 for (unsigned int r = 0; r < n_block_rows(); ++r)
1549 for (unsigned int c = 0; c < n_block_cols(); ++c)
1550 {
1551 MatrixType *p = this->sub_objects[r][c];
1552 this->sub_objects[r][c] = nullptr;
1553 delete p;
1554 }
1555 sub_objects.reinit(0, 0);
1556
1557 // reset block indices to empty
1558 row_block_indices = column_block_indices = BlockIndices();
1559 }
1560
1561
1562
1563 template <typename MatrixType>
1564 inline typename BlockMatrixBase<MatrixType>::BlockType &
1565 BlockMatrixBase<MatrixType>::block(const unsigned int row,
1566 const unsigned int column)
1567 {
1568 AssertIndexRange(row, n_block_rows());
1569 AssertIndexRange(column, n_block_cols());
1570
1571 return *sub_objects[row][column];
1572 }
1573
1574
1575
1576 template <typename MatrixType>
1577 inline const typename BlockMatrixBase<MatrixType>::BlockType &
1578 BlockMatrixBase<MatrixType>::block(const unsigned int row,
1579 const unsigned int column) const
1580 {
1581 AssertIndexRange(row, n_block_rows());
1582 AssertIndexRange(column, n_block_cols());
1583
1584 return *sub_objects[row][column];
1585 }
1586
1587
1588 template <typename MatrixType>
1589 inline typename BlockMatrixBase<MatrixType>::size_type
1590 BlockMatrixBase<MatrixType>::m() const
1591 {
1592 return row_block_indices.total_size();
1593 }
1594
1595
1596
1597 template <typename MatrixType>
1598 inline typename BlockMatrixBase<MatrixType>::size_type
1599 BlockMatrixBase<MatrixType>::n() const
1600 {
1601 return column_block_indices.total_size();
1602 }
1603
1604
1605
1606 template <typename MatrixType>
1607 inline unsigned int
1608 BlockMatrixBase<MatrixType>::n_block_cols() const
1609 {
1610 return column_block_indices.size();
1611 }
1612
1613
1614
1615 template <typename MatrixType>
1616 inline unsigned int
1617 BlockMatrixBase<MatrixType>::n_block_rows() const
1618 {
1619 return row_block_indices.size();
1620 }
1621
1622
1623
1624 // Write the single set manually,
1625 // since the other function has a lot
1626 // of overhead in that case.
1627 template <typename MatrixType>
1628 inline void
1629 BlockMatrixBase<MatrixType>::set(const size_type i,
1630 const size_type j,
1631 const value_type value)
1632 {
1633 prepare_set_operation();
1634
1635 AssertIsFinite(value);
1636
1637 const std::pair<unsigned int, size_type>
1638 row_index = row_block_indices.global_to_local(i),
1639 col_index = column_block_indices.global_to_local(j);
1640 block(row_index.first, col_index.first)
1641 .set(row_index.second, col_index.second, value);
1642 }
1643
1644
1645
1646 template <typename MatrixType>
1647 template <typename number>
1648 inline void
1649 BlockMatrixBase<MatrixType>::set(const std::vector<size_type> &row_indices,
1650 const std::vector<size_type> &col_indices,
1651 const FullMatrix<number> &values,
1652 const bool elide_zero_values)
1653 {
1654 Assert(row_indices.size() == values.m(),
1655 ExcDimensionMismatch(row_indices.size(), values.m()));
1656 Assert(col_indices.size() == values.n(),
1657 ExcDimensionMismatch(col_indices.size(), values.n()));
1658
1659 for (size_type i = 0; i < row_indices.size(); ++i)
1660 set(row_indices[i],
1661 col_indices.size(),
1662 col_indices.data(),
1663 &values(i, 0),
1664 elide_zero_values);
1665 }
1666
1667
1668
1669 template <typename MatrixType>
1670 template <typename number>
1671 inline void
1672 BlockMatrixBase<MatrixType>::set(const std::vector<size_type> &indices,
1673 const FullMatrix<number> &values,
1674 const bool elide_zero_values)
1675 {
1676 Assert(indices.size() == values.m(),
1677 ExcDimensionMismatch(indices.size(), values.m()));
1678 Assert(values.n() == values.m(), ExcNotQuadratic());
1679
1680 for (size_type i = 0; i < indices.size(); ++i)
1681 set(indices[i],
1682 indices.size(),
1683 indices.data(),
1684 &values(i, 0),
1685 elide_zero_values);
1686 }
1687
1688
1689
1690 template <typename MatrixType>
1691 template <typename number>
1692 inline void
1693 BlockMatrixBase<MatrixType>::set(const size_type row,
1694 const std::vector<size_type> &col_indices,
1695 const std::vector<number> &values,
1696 const bool elide_zero_values)
1697 {
1698 Assert(col_indices.size() == values.size(),
1699 ExcDimensionMismatch(col_indices.size(), values.size()));
1700
1701 set(row,
1702 col_indices.size(),
1703 col_indices.data(),
1704 values.data(),
1705 elide_zero_values);
1706 }
1707
1708
1709
1710 // This is a very messy function, since
1711 // we need to calculate to each position
1712 // the location in the global array.
1713 template <typename MatrixType>
1714 template <typename number>
1715 inline void
1716 BlockMatrixBase<MatrixType>::set(const size_type row,
1717 const size_type n_cols,
1718 const size_type *col_indices,
1719 const number *values,
1720 const bool elide_zero_values)
1721 {
1722 prepare_set_operation();
1723
1724 // lock access to the temporary data structure to
1725 // allow multiple threads to call this function concurrently
1726 std::lock_guard<std::mutex> lock(temporary_data.mutex);
1727
1728 // Resize scratch arrays
1729 if (temporary_data.column_indices.size() < this->n_block_cols())
1730 {
1731 temporary_data.column_indices.resize(this->n_block_cols());
1732 temporary_data.column_values.resize(this->n_block_cols());
1733 temporary_data.counter_within_block.resize(this->n_block_cols());
1734 }
1735
1736 // Resize sub-arrays to n_cols. This
1737 // is a bit wasteful, but we resize
1738 // only a few times (then the maximum
1739 // row length won't increase that
1740 // much any more). At least we know
1741 // that all arrays are going to be of
1742 // the same size, so we can check
1743 // whether the size of one is large
1744 // enough before actually going
1745 // through all of them.
1746 if (temporary_data.column_indices[0].size() < n_cols)
1747 {
1748 for (unsigned int i = 0; i < this->n_block_cols(); ++i)
1749 {
1750 temporary_data.column_indices[i].resize(n_cols);
1751 temporary_data.column_values[i].resize(n_cols);
1752 }
1753 }
1754
1755 // Reset the number of added elements
1756 // in each block to zero.
1757 for (unsigned int i = 0; i < this->n_block_cols(); ++i)
1758 temporary_data.counter_within_block[i] = 0;
1759
1760 // Go through the column indices to
1761 // find out which portions of the
1762 // values should be set in which
1763 // block of the matrix. We need to
1764 // touch all the data, since we can't
1765 // be sure that the data of one block
1766 // is stored contiguously (in fact,
1767 // indices will be intermixed when it
1768 // comes from an element matrix).
1769 for (size_type j = 0; j < n_cols; ++j)
1770 {
1771 number value = values[j];
1772
1773 if (value == number() && elide_zero_values == true)
1774 continue;
1775
1776 const std::pair<unsigned int, size_type> col_index =
1777 this->column_block_indices.global_to_local(col_indices[j]);
1778
1779 const size_type local_index =
1780 temporary_data.counter_within_block[col_index.first]++;
1781
1782 temporary_data.column_indices[col_index.first][local_index] =
1783 col_index.second;
1784 temporary_data.column_values[col_index.first][local_index] = value;
1785 }
1786
1787 if constexpr (running_in_debug_mode())
1788 {
1789 // If in debug mode, do a check whether
1790 // the right length has been obtained.
1791 size_type length = 0;
1792 for (unsigned int i = 0; i < this->n_block_cols(); ++i)
1793 length += temporary_data.counter_within_block[i];
1794 Assert(length <= n_cols, ExcInternalError());
1795 }
1796
1797 // Now we found out about where the
1798 // individual columns should start and
1799 // where we should start reading out
1800 // data. Now let's write the data into
1801 // the individual blocks!
1802 const std::pair<unsigned int, size_type> row_index =
1803 this->row_block_indices.global_to_local(row);
1804 for (unsigned int block_col = 0; block_col < n_block_cols(); ++block_col)
1805 {
1806 if (temporary_data.counter_within_block[block_col] == 0)
1807 continue;
1808
1809 block(row_index.first, block_col)
1810 .set(row_index.second,
1811 temporary_data.counter_within_block[block_col],
1812 temporary_data.column_indices[block_col].data(),
1813 temporary_data.column_values[block_col].data(),
1814 false);
1815 }
1816 }
1817
1818
1819
1820 template <typename MatrixType>
1821 inline void
1822 BlockMatrixBase<MatrixType>::add(const size_type i,
1823 const size_type j,
1824 const value_type value)
1825 {
1826 AssertIsFinite(value);
1827
1828 prepare_add_operation();
1829
1830 // save some cycles for zero additions, but
1831 // only if it is safe for the matrix we are
1832 // working with
1833 using MatrixTraits = typename MatrixType::Traits;
1834 if ((MatrixTraits::zero_addition_can_be_elided == true) &&
1835 (value == value_type()))
1836 return;
1837
1838 const std::pair<unsigned int, size_type>
1839 row_index = row_block_indices.global_to_local(i),
1840 col_index = column_block_indices.global_to_local(j);
1841 block(row_index.first, col_index.first)
1842 .add(row_index.second, col_index.second, value);
1843 }
1844
1845
1846
1847 template <typename MatrixType>
1848 template <typename number>
1849 inline void
1850 BlockMatrixBase<MatrixType>::add(const std::vector<size_type> &row_indices,
1851 const std::vector<size_type> &col_indices,
1852 const FullMatrix<number> &values,
1853 const bool elide_zero_values)
1854 {
1855 Assert(row_indices.size() == values.m(),
1856 ExcDimensionMismatch(row_indices.size(), values.m()));
1857 Assert(col_indices.size() == values.n(),
1858 ExcDimensionMismatch(col_indices.size(), values.n()));
1859
1860 for (size_type i = 0; i < row_indices.size(); ++i)
1861 add(row_indices[i],
1862 col_indices.size(),
1863 col_indices.data(),
1864 &values(i, 0),
1865 elide_zero_values);
1866 }
1867
1868
1869
1870 template <typename MatrixType>
1871 template <typename number>
1872 inline void
1873 BlockMatrixBase<MatrixType>::add(const std::vector<size_type> &indices,
1874 const FullMatrix<number> &values,
1875 const bool elide_zero_values)
1876 {
1877 Assert(indices.size() == values.m(),
1878 ExcDimensionMismatch(indices.size(), values.m()));
1879 Assert(values.n() == values.m(), ExcNotQuadratic());
1880
1881 for (size_type i = 0; i < indices.size(); ++i)
1882 add(indices[i],
1883 indices.size(),
1884 indices.data(),
1885 &values(i, 0),
1886 elide_zero_values);
1887 }
1888
1889
1890
1891 template <typename MatrixType>
1892 template <typename number>
1893 inline void
1894 BlockMatrixBase<MatrixType>::add(const size_type row,
1895 const std::vector<size_type> &col_indices,
1896 const std::vector<number> &values,
1897 const bool elide_zero_values)
1898 {
1899 Assert(col_indices.size() == values.size(),
1900 ExcDimensionMismatch(col_indices.size(), values.size()));
1901
1902 add(row,
1903 col_indices.size(),
1904 col_indices.data(),
1905 values.data(),
1906 elide_zero_values);
1907 }
1908
1909
1910
1911 // This is a very messy function, since
1912 // we need to calculate to each position
1913 // the location in the global array.
1914 template <typename MatrixType>
1915 template <typename number>
1916 inline void
1917 BlockMatrixBase<MatrixType>::add(const size_type row,
1918 const size_type n_cols,
1919 const size_type *col_indices,
1920 const number *values,
1921 const bool elide_zero_values,
1922 const bool col_indices_are_sorted)
1923 {
1924 prepare_add_operation();
1925
1926 // TODO: Look over this to find out
1927 // whether we can do that more
1928 // efficiently.
1929 if (col_indices_are_sorted == true)
1930 {
1931 if constexpr (running_in_debug_mode())
1932 {
1933 // check whether indices really are
1934 // sorted.
1935 size_type before = col_indices[0];
1936 for (size_type i = 1; i < n_cols; ++i)
1937 if (col_indices[i] <= before)
1938 {
1939 Assert(false,
1940 ExcMessage("Flag col_indices_are_sorted is set, but "
1941 "indices appear to not be sorted."));
1942 }
1943 else
1944 before = col_indices[i];
1945 }
1946 const std::pair<unsigned int, size_type> row_index =
1947 this->row_block_indices.global_to_local(row);
1948
1949 if (this->n_block_cols() > 1)
1950 {
1951 const size_type *first_block =
1952 Utilities::lower_bound(col_indices,
1953 col_indices + n_cols,
1954 this->column_block_indices.block_start(1));
1955
1956 const size_type n_zero_block_indices = first_block - col_indices;
1957 block(row_index.first, 0)
1958 .add(row_index.second,
1959 n_zero_block_indices,
1960 col_indices,
1961 values,
1962 elide_zero_values,
1963 col_indices_are_sorted);
1964
1965 if (n_zero_block_indices < n_cols)
1966 this->add(row,
1967 n_cols - n_zero_block_indices,
1968 first_block,
1969 values + n_zero_block_indices,
1970 elide_zero_values,
1971 false);
1972 }
1973 else
1974 {
1975 block(row_index.first, 0)
1976 .add(row_index.second,
1977 n_cols,
1978 col_indices,
1979 values,
1980 elide_zero_values,
1981 col_indices_are_sorted);
1982 }
1983
1984 return;
1985 }
1986
1987 // Lock scratch arrays, then resize them
1988 std::lock_guard<std::mutex> lock(temporary_data.mutex);
1989
1990 if (temporary_data.column_indices.size() < this->n_block_cols())
1991 {
1992 temporary_data.column_indices.resize(this->n_block_cols());
1993 temporary_data.column_values.resize(this->n_block_cols());
1994 temporary_data.counter_within_block.resize(this->n_block_cols());
1995 }
1996
1997 // Resize sub-arrays to n_cols. This
1998 // is a bit wasteful, but we resize
1999 // only a few times (then the maximum
2000 // row length won't increase that
2001 // much any more). At least we know
2002 // that all arrays are going to be of
2003 // the same size, so we can check
2004 // whether the size of one is large
2005 // enough before actually going
2006 // through all of them.
2007 if (temporary_data.column_indices[0].size() < n_cols)
2008 {
2009 for (unsigned int i = 0; i < this->n_block_cols(); ++i)
2010 {
2011 temporary_data.column_indices[i].resize(n_cols);
2012 temporary_data.column_values[i].resize(n_cols);
2013 }
2014 }
2015
2016 // Reset the number of added elements
2017 // in each block to zero.
2018 for (unsigned int i = 0; i < this->n_block_cols(); ++i)
2019 temporary_data.counter_within_block[i] = 0;
2020
2021 // Go through the column indices to
2022 // find out which portions of the
2023 // values should be written into
2024 // which block of the matrix. We need
2025 // to touch all the data, since we
2026 // can't be sure that the data of one
2027 // block is stored contiguously (in
2028 // fact, data will be intermixed when
2029 // it comes from an element matrix).
2030 for (size_type j = 0; j < n_cols; ++j)
2031 {
2032 number value = values[j];
2033
2034 if (value == number() && elide_zero_values == true)
2035 continue;
2036
2037 const std::pair<unsigned int, size_type> col_index =
2038 this->column_block_indices.global_to_local(col_indices[j]);
2039
2040 const size_type local_index =
2041 temporary_data.counter_within_block[col_index.first]++;
2042
2043 temporary_data.column_indices[col_index.first][local_index] =
2044 col_index.second;
2045 temporary_data.column_values[col_index.first][local_index] = value;
2046 }
2047
2048 if constexpr (running_in_debug_mode())
2049 {
2050 // If in debug mode, do a check whether
2051 // the right length has been obtained.
2052 size_type length = 0;
2053 for (unsigned int i = 0; i < this->n_block_cols(); ++i)
2054 length += temporary_data.counter_within_block[i];
2055 Assert(length <= n_cols, ExcInternalError());
2056 }
2057
2058 // Now we found out about where the
2059 // individual columns should start and
2060 // where we should start reading out
2061 // data. Now let's write the data into
2062 // the individual blocks!
2063 const std::pair<unsigned int, size_type> row_index =
2064 this->row_block_indices.global_to_local(row);
2065 for (unsigned int block_col = 0; block_col < n_block_cols(); ++block_col)
2066 {
2067 if (temporary_data.counter_within_block[block_col] == 0)
2068 continue;
2069
2070 block(row_index.first, block_col)
2071 .add(row_index.second,
2072 temporary_data.counter_within_block[block_col],
2073 temporary_data.column_indices[block_col].data(),
2074 temporary_data.column_values[block_col].data(),
2075 false,
2076 col_indices_are_sorted);
2077 }
2078 }
2079
2080
2081
2082 template <typename MatrixType>
2083 inline void
2084 BlockMatrixBase<MatrixType>::add(const value_type factor,
2085 const BlockMatrixBase<MatrixType> &matrix)
2086 {
2087 AssertIsFinite(factor);
2088
2089 prepare_add_operation();
2090
2091 // save some cycles for zero additions, but
2092 // only if it is safe for the matrix we are
2093 // working with
2094 using MatrixTraits = typename MatrixType::Traits;
2095 if ((MatrixTraits::zero_addition_can_be_elided == true) && (factor == 0))
2096 return;
2097
2098 for (unsigned int row = 0; row < n_block_rows(); ++row)
2099 for (unsigned int col = 0; col < n_block_cols(); ++col)
2100 // This function should throw if the sparsity
2101 // patterns of the two blocks differ
2102 block(row, col).add(factor, matrix.block(row, col));
2103 }
2104
2105
2106
2107 template <typename MatrixType>
2108 inline typename BlockMatrixBase<MatrixType>::value_type
2109 BlockMatrixBase<MatrixType>::operator()(const size_type i,
2110 const size_type j) const
2111 {
2112 const std::pair<unsigned int, size_type>
2113 row_index = row_block_indices.global_to_local(i),
2114 col_index = column_block_indices.global_to_local(j);
2115 return block(row_index.first, col_index.first)(row_index.second,
2116 col_index.second);
2117 }
2118
2119
2120
2121 template <typename MatrixType>
2122 inline typename BlockMatrixBase<MatrixType>::value_type
2123 BlockMatrixBase<MatrixType>::el(const size_type i, const size_type j) const
2124 {
2125 const std::pair<unsigned int, size_type>
2126 row_index = row_block_indices.global_to_local(i),
2127 col_index = column_block_indices.global_to_local(j);
2128 return block(row_index.first, col_index.first)
2129 .el(row_index.second, col_index.second);
2130 }
2131
2132
2133
2134 template <typename MatrixType>
2135 inline typename BlockMatrixBase<MatrixType>::value_type
2136 BlockMatrixBase<MatrixType>::diag_element(const size_type i) const
2137 {
2138 Assert(n_block_rows() == n_block_cols(), ExcNotQuadratic());
2139
2140 const std::pair<unsigned int, size_type> index =
2141 row_block_indices.global_to_local(i);
2142 return block(index.first, index.first).diag_element(index.second);
2143 }
2144
2145
2146
2147 template <typename MatrixType>
2148 inline void
2149 BlockMatrixBase<MatrixType>::compress(VectorOperation::values operation)
2150 {
2151 for (unsigned int r = 0; r < n_block_rows(); ++r)
2152 for (unsigned int c = 0; c < n_block_cols(); ++c)
2153 block(r, c).compress(operation);
2154 }
2155
2156
2157
2158 template <typename MatrixType>
2159 inline BlockMatrixBase<MatrixType> &
2160 BlockMatrixBase<MatrixType>::operator*=(const value_type factor)
2161 {
2162 Assert(n_block_cols() != 0, ExcNotInitialized());
2163 Assert(n_block_rows() != 0, ExcNotInitialized());
2164
2165 for (unsigned int r = 0; r < n_block_rows(); ++r)
2166 for (unsigned int c = 0; c < n_block_cols(); ++c)
2167 block(r, c) *= factor;
2168
2169 return *this;
2170 }
2171
2172
2173
2174 template <typename MatrixType>
2175 inline BlockMatrixBase<MatrixType> &
2176 BlockMatrixBase<MatrixType>::operator/=(const value_type factor)
2177 {
2178 Assert(n_block_cols() != 0, ExcNotInitialized());
2179 Assert(n_block_rows() != 0, ExcNotInitialized());
2180 Assert(factor != 0, ExcDivideByZero());
2181
2182 const value_type factor_inv = 1. / factor;
2183
2184 for (unsigned int r = 0; r < n_block_rows(); ++r)
2185 for (unsigned int c = 0; c < n_block_cols(); ++c)
2186 block(r, c) *= factor_inv;
2187
2188 return *this;
2189 }
2190
2191
2192
2193 template <typename MatrixType>
2194 const BlockIndices &
2195 BlockMatrixBase<MatrixType>::get_row_indices() const
2196 {
2197 return this->row_block_indices;
2198 }
2199
2200
2201
2202 template <typename MatrixType>
2203 const BlockIndices &
2204 BlockMatrixBase<MatrixType>::get_column_indices() const
2205 {
2206 return this->column_block_indices;
2207 }
2208
2209
2210
2211 template <typename MatrixType>
2212 template <typename BlockVectorType>
2213 void
2214 BlockMatrixBase<MatrixType>::vmult_block_block(BlockVectorType &dst,
2215 const BlockVectorType &src) const
2216 {
2217 Assert(dst.n_blocks() == n_block_rows(),
2218 ExcDimensionMismatch(dst.n_blocks(), n_block_rows()));
2219 Assert(src.n_blocks() == n_block_cols(),
2220 ExcDimensionMismatch(src.n_blocks(), n_block_cols()));
2221
2222 for (size_type row = 0; row < n_block_rows(); ++row)
2223 {
2224 block(row, 0).vmult(dst.block(row), src.block(0));
2225 for (size_type col = 1; col < n_block_cols(); ++col)
2226 block(row, col).vmult_add(dst.block(row), src.block(col));
2227 };
2228 }
2229
2230
2231
2232 template <typename MatrixType>
2233 template <typename BlockVectorType, typename VectorType>
2234 void
2235 BlockMatrixBase<MatrixType>::vmult_nonblock_block(
2236 VectorType &dst,
2237 const BlockVectorType &src) const
2238 {
2239 Assert(n_block_rows() == 1, ExcDimensionMismatch(1, n_block_rows()));
2240 Assert(src.n_blocks() == n_block_cols(),
2241 ExcDimensionMismatch(src.n_blocks(), n_block_cols()));
2242
2243 block(0, 0).vmult(dst, src.block(0));
2244 for (size_type col = 1; col < n_block_cols(); ++col)
2245 block(0, col).vmult_add(dst, src.block(col));
2246 }
2247
2248
2249
2250 template <typename MatrixType>
2251 template <typename BlockVectorType, typename VectorType>
2252 void
2253 BlockMatrixBase<MatrixType>::vmult_block_nonblock(BlockVectorType &dst,
2254 const VectorType &src) const
2255 {
2256 Assert(dst.n_blocks() == n_block_rows(),
2257 ExcDimensionMismatch(dst.n_blocks(), n_block_rows()));
2258 Assert(1 == n_block_cols(), ExcDimensionMismatch(1, n_block_cols()));
2259
2260 for (size_type row = 0; row < n_block_rows(); ++row)
2261 block(row, 0).vmult(dst.block(row), src);
2262 }
2263
2264
2265
2266 template <typename MatrixType>
2267 template <typename VectorType>
2268 void
2269 BlockMatrixBase<MatrixType>::vmult_nonblock_nonblock(
2270 VectorType &dst,
2271 const VectorType &src) const
2272 {
2273 Assert(1 == n_block_rows(), ExcDimensionMismatch(1, n_block_rows()));
2274 Assert(1 == n_block_cols(), ExcDimensionMismatch(1, n_block_cols()));
2275
2276 block(0, 0).vmult(dst, src);
2277 }
2278
2279
2280
2281 template <typename MatrixType>
2282 template <typename BlockVectorType>
2283 void
2284 BlockMatrixBase<MatrixType>::vmult_add(BlockVectorType &dst,
2285 const BlockVectorType &src) const
2286 {
2287 Assert(dst.n_blocks() == n_block_rows(),
2288 ExcDimensionMismatch(dst.n_blocks(), n_block_rows()));
2289 Assert(src.n_blocks() == n_block_cols(),
2290 ExcDimensionMismatch(src.n_blocks(), n_block_cols()));
2291
2292 for (unsigned int row = 0; row < n_block_rows(); ++row)
2293 for (unsigned int col = 0; col < n_block_cols(); ++col)
2294 block(row, col).vmult_add(dst.block(row), src.block(col));
2295 }
2296
2297
2298
2299 template <typename MatrixType>
2300 template <typename BlockVectorType>
2301 void
2302 BlockMatrixBase<MatrixType>::Tvmult_block_block(
2303 BlockVectorType &dst,
2304 const BlockVectorType &src) const
2305 {
2306 Assert(dst.n_blocks() == n_block_cols(),
2307 ExcDimensionMismatch(dst.n_blocks(), n_block_cols()));
2308 Assert(src.n_blocks() == n_block_rows(),
2309 ExcDimensionMismatch(src.n_blocks(), n_block_rows()));
2310
2311 dst = 0.;
2312
2313 for (unsigned int row = 0; row < n_block_rows(); ++row)
2314 {
2315 for (unsigned int col = 0; col < n_block_cols(); ++col)
2316 block(row, col).Tvmult_add(dst.block(col), src.block(row));
2317 };
2318 }
2319
2320
2321
2322 template <typename MatrixType>
2323 template <typename BlockVectorType, typename VectorType>
2324 void
2325 BlockMatrixBase<MatrixType>::Tvmult_block_nonblock(BlockVectorType &dst,
2326 const VectorType &src) const
2327 {
2328 Assert(dst.n_blocks() == n_block_cols(),
2329 ExcDimensionMismatch(dst.n_blocks(), n_block_cols()));
2330 Assert(1 == n_block_rows(), ExcDimensionMismatch(1, n_block_rows()));
2331
2332 dst = 0.;
2333
2334 for (unsigned int col = 0; col < n_block_cols(); ++col)
2335 block(0, col).Tvmult_add(dst.block(col), src);
2336 }
2337
2338
2339
2340 template <typename MatrixType>
2341 template <typename BlockVectorType, typename VectorType>
2342 void
2343 BlockMatrixBase<MatrixType>::Tvmult_nonblock_block(
2344 VectorType &dst,
2345 const BlockVectorType &src) const
2346 {
2347 Assert(1 == n_block_cols(), ExcDimensionMismatch(1, n_block_cols()));
2348 Assert(src.n_blocks() == n_block_rows(),
2349 ExcDimensionMismatch(src.n_blocks(), n_block_rows()));
2350
2351 block(0, 0).Tvmult(dst, src.block(0));
2352
2353 for (size_type row = 1; row < n_block_rows(); ++row)
2354 block(row, 0).Tvmult_add(dst, src.block(row));
2355 }
2356
2357
2358
2359 template <typename MatrixType>
2360 template <typename VectorType>
2361 void
2362 BlockMatrixBase<MatrixType>::Tvmult_nonblock_nonblock(
2363 VectorType &dst,
2364 const VectorType &src) const
2365 {
2366 Assert(1 == n_block_cols(), ExcDimensionMismatch(1, n_block_cols()));
2367 Assert(1 == n_block_rows(), ExcDimensionMismatch(1, n_block_rows()));
2368
2369 block(0, 0).Tvmult(dst, src);
2370 }
2371
2372
2373
2374 template <typename MatrixType>
2375 template <typename BlockVectorType>
2376 void
2377 BlockMatrixBase<MatrixType>::Tvmult_add(BlockVectorType &dst,
2378 const BlockVectorType &src) const
2379 {
2380 Assert(dst.n_blocks() == n_block_cols(),
2381 ExcDimensionMismatch(dst.n_blocks(), n_block_cols()));
2382 Assert(src.n_blocks() == n_block_rows(),
2383 ExcDimensionMismatch(src.n_blocks(), n_block_rows()));
2384
2385 for (unsigned int row = 0; row < n_block_rows(); ++row)
2386 for (unsigned int col = 0; col < n_block_cols(); ++col)
2387 block(row, col).Tvmult_add(dst.block(col), src.block(row));
2388 }
2389
2390
2391
2392 template <typename MatrixType>
2393 template <typename BlockVectorType>
2394 typename BlockMatrixBase<MatrixType>::value_type
2395 BlockMatrixBase<MatrixType>::matrix_norm_square(const BlockVectorType &v) const
2396 {
2397 Assert(n_block_rows() == n_block_cols(), ExcNotQuadratic());
2398 Assert(v.n_blocks() == n_block_rows(),
2399 ExcDimensionMismatch(v.n_blocks(), n_block_rows()));
2400
2401 value_type norm_sqr = 0;
2402 for (unsigned int row = 0; row < n_block_rows(); ++row)
2403 for (unsigned int col = 0; col < n_block_cols(); ++col)
2404 if (row == col)
2405 norm_sqr += block(row, col).matrix_norm_square(v.block(row));
2406 else
2407 norm_sqr +=
2408 block(row, col).matrix_scalar_product(v.block(row), v.block(col));
2409 return norm_sqr;
2410 }
2411
2412
2413
2414 template <typename MatrixType>
2415 typename BlockMatrixBase<MatrixType>::real_type
2416 BlockMatrixBase<MatrixType>::frobenius_norm() const
2417 {
2418 value_type norm_sqr = 0;
2419
2420 // For each block, get the Frobenius norm, and add the square to the
2421 // accumulator for the full matrix
2422 for (unsigned int row = 0; row < n_block_rows(); ++row)
2423 {
2424 for (unsigned int col = 0; col < n_block_cols(); ++col)
2425 {
2426 const value_type block_norm = block(row, col).frobenius_norm();
2427 norm_sqr += block_norm * block_norm;
2428 }
2429 }
2430
2431 return std::sqrt(norm_sqr);
2432 }
2433
2434
2435
2436 template <typename MatrixType>
2437 template <typename BlockVectorType>
2438 typename BlockMatrixBase<MatrixType>::value_type
2439 BlockMatrixBase<MatrixType>::matrix_scalar_product(
2440 const BlockVectorType &u,
2441 const BlockVectorType &v) const
2442 {
2443 Assert(u.n_blocks() == n_block_rows(),
2444 ExcDimensionMismatch(u.n_blocks(), n_block_rows()));
2445 Assert(v.n_blocks() == n_block_cols(),
2446 ExcDimensionMismatch(v.n_blocks(), n_block_cols()));
2447
2448 value_type result = 0;
2449 for (unsigned int row = 0; row < n_block_rows(); ++row)
2450 for (unsigned int col = 0; col < n_block_cols(); ++col)
2451 result +=
2452 block(row, col).matrix_scalar_product(u.block(row), v.block(col));
2453 return result;
2454 }
2455
2456
2457
2458 template <typename MatrixType>
2459 template <typename BlockVectorType>
2460 typename BlockMatrixBase<MatrixType>::value_type
2461 BlockMatrixBase<MatrixType>::residual(BlockVectorType &dst,
2462 const BlockVectorType &x,
2463 const BlockVectorType &b) const
2464 {
2465 Assert(dst.n_blocks() == n_block_rows(),
2466 ExcDimensionMismatch(dst.n_blocks(), n_block_rows()));
2467 Assert(b.n_blocks() == n_block_rows(),
2468 ExcDimensionMismatch(b.n_blocks(), n_block_rows()));
2469 Assert(x.n_blocks() == n_block_cols(),
2470 ExcDimensionMismatch(x.n_blocks(), n_block_cols()));
2471 // in block notation, the residual is
2472 // r_i = b_i - \sum_j A_ij x_j.
2473 // this can be written as
2474 // r_i = b_i - A_i0 x_0 - \sum_{j>0} A_ij x_j.
2475 //
2476 // for the first two terms, we can
2477 // call the residual function of
2478 // A_i0. for the other terms, we
2479 // use vmult_add. however, we want
2480 // to subtract, so in order to
2481 // avoid a temporary vector, we
2482 // perform a sign change of the
2483 // first two term before, and after
2484 // adding up
2485 for (unsigned int row = 0; row < n_block_rows(); ++row)
2486 {
2487 block(row, 0).residual(dst.block(row), x.block(0), b.block(row));
2488
2489 for (size_type i = 0; i < dst.block(row).size(); ++i)
2490 dst.block(row)(i) = -dst.block(row)(i);
2491
2492 for (unsigned int col = 1; col < n_block_cols(); ++col)
2493 block(row, col).vmult_add(dst.block(row), x.block(col));
2494
2495 for (size_type i = 0; i < dst.block(row).size(); ++i)
2496 dst.block(row)(i) = -dst.block(row)(i);
2497 };
2498
2499 value_type res = 0;
2500 for (size_type row = 0; row < n_block_rows(); ++row)
2501 res += dst.block(row).norm_sqr();
2502 return std::sqrt(res);
2503 }
2504
2505
2506
2507 template <typename MatrixType>
2508 inline void
2509 BlockMatrixBase<MatrixType>::print(std::ostream &out,
2510 const bool alternative_output) const
2511 {
2512 for (unsigned int row = 0; row < n_block_rows(); ++row)
2513 for (unsigned int col = 0; col < n_block_cols(); ++col)
2514 {
2515 if (!alternative_output)
2516 out << "Block (" << row << ", " << col << ')' << std::endl;
2517
2518 block(row, col).print(out, alternative_output);
2519 }
2520 }
2521
2522
2523
2524 template <typename MatrixType>
2525 inline typename BlockMatrixBase<MatrixType>::const_iterator
2526 BlockMatrixBase<MatrixType>::begin() const
2527 {
2528 return const_iterator(this, 0);
2529 }
2530
2531
2532
2533 template <typename MatrixType>
2534 inline typename BlockMatrixBase<MatrixType>::const_iterator
2535 BlockMatrixBase<MatrixType>::end() const
2536 {
2537 return const_iterator(this, m());
2538 }
2539
2540
2541
2542 template <typename MatrixType>
2543 inline typename BlockMatrixBase<MatrixType>::const_iterator
2544 BlockMatrixBase<MatrixType>::begin(const size_type r) const
2545 {
2546 AssertIndexRange(r, m());
2547 return const_iterator(this, r);
2548 }
2549
2550
2551
2552 template <typename MatrixType>
2553 inline typename BlockMatrixBase<MatrixType>::const_iterator
2554 BlockMatrixBase<MatrixType>::end(const size_type r) const
2555 {
2556 AssertIndexRange(r, m());
2557 return const_iterator(this, r + 1);
2558 }
2559
2560
2561
2562 template <typename MatrixType>
2563 inline typename BlockMatrixBase<MatrixType>::iterator
2564 BlockMatrixBase<MatrixType>::begin()
2565 {
2566 return iterator(this, 0);
2567 }
2568
2569
2570
2571 template <typename MatrixType>
2572 inline typename BlockMatrixBase<MatrixType>::iterator
2573 BlockMatrixBase<MatrixType>::end()
2574 {
2575 return iterator(this, m());
2576 }
2577
2578
2579
2580 template <typename MatrixType>
2581 inline typename BlockMatrixBase<MatrixType>::iterator
2582 BlockMatrixBase<MatrixType>::begin(const size_type r)
2583 {
2584 AssertIndexRange(r, m());
2585 return iterator(this, r);
2586 }
2587
2588
2589
2590 template <typename MatrixType>
2591 inline typename BlockMatrixBase<MatrixType>::iterator
2592 BlockMatrixBase<MatrixType>::end(const size_type r)
2593 {
2594 AssertIndexRange(r, m());
2595 return iterator(this, r + 1);
2596 }
2597
2598
2599
2600 template <typename MatrixType>
2601 void
2602 BlockMatrixBase<MatrixType>::collect_sizes()
2603 {
2604 std::vector<size_type> row_sizes(this->n_block_rows());
2605 std::vector<size_type> col_sizes(this->n_block_cols());
2606
2607 // first find out the row sizes
2608 // from the first block column
2609 for (unsigned int r = 0; r < this->n_block_rows(); ++r)
2610 row_sizes[r] = sub_objects[r][0]->m();
2611 // then check that the following
2612 // block columns have the same
2613 // sizes
2614 for (unsigned int c = 1; c < this->n_block_cols(); ++c)
2615 for (unsigned int r = 0; r < this->n_block_rows(); ++r)
2616 Assert(row_sizes[r] == sub_objects[r][c]->m(),
2617 ExcIncompatibleRowNumbers(r, 0, r, c));
2618
2619 // finally initialize the row
2620 // indices with this array
2621 this->row_block_indices.reinit(row_sizes);
2622
2623
2624 // then do the same with the columns
2625 for (unsigned int c = 0; c < this->n_block_cols(); ++c)
2626 col_sizes[c] = sub_objects[0][c]->n();
2627 for (unsigned int r = 1; r < this->n_block_rows(); ++r)
2628 for (unsigned int c = 0; c < this->n_block_cols(); ++c)
2629 Assert(col_sizes[c] == sub_objects[r][c]->n(),
2630 ExcIncompatibleRowNumbers(0, c, r, c));
2631
2632 // finally initialize the row
2633 // indices with this array
2634 this->column_block_indices.reinit(col_sizes);
2635 }
2636
2637
2638
2639 template <typename MatrixType>
2640 void
2641 BlockMatrixBase<MatrixType>::prepare_add_operation()
2642 {
2643 for (unsigned int row = 0; row < n_block_rows(); ++row)
2644 for (unsigned int col = 0; col < n_block_cols(); ++col)
2645 block(row, col).prepare_add();
2646 }
2647
2648
2649
2650 template <typename MatrixType>
2651 void
2652 BlockMatrixBase<MatrixType>::prepare_set_operation()
2653 {
2654 for (unsigned int row = 0; row < n_block_rows(); ++row)
2655 for (unsigned int col = 0; col < n_block_cols(); ++col)
2656 block(row, col).prepare_set();
2657 }
2658
2659 #endif // DOXYGEN
2660
2661
2662 DEAL_II_NAMESPACE_CLOSE
2663
2664 #endif // dealii_block_matrix_base_h