Debian Codegraph @

include/deal.II/lac/affine_constraints.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 1998 - 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_affine_constraints_h
16 #define dealii_affine_constraints_h
17
18 #include <deal.II/base/config.h>
19
20 #include <deal.II/base/enable_observer_pointer.h>
21 #include <deal.II/base/exceptions.h>
22 #include <deal.II/base/index_set.h>
23 #include <deal.II/base/table.h>
24 #include <deal.II/base/template_constraints.h>
25 #include <deal.II/base/thread_local_storage.h>
26
27 #include <deal.II/lac/sparsity_pattern_base.h>
28 #include <deal.II/lac/vector.h>
29 #include <deal.II/lac/vector_element_access.h>
30
31 #include <boost/range/iterator_range.hpp>
32
33 #include <algorithm>
34 #include <set>
35 #include <type_traits>
36 #include <utility>
37 #include <vector>
38
39 DEAL_II_NAMESPACE_OPEN
40
41 // Forward declarations
42 #ifndef DOXYGEN
43 template <typename>
44 class FullMatrix;
45 class SparsityPattern;
46 class DynamicSparsityPattern;
47 class BlockSparsityPattern;
48 class BlockDynamicSparsityPattern;
49 template <typename number>
50 class SparseMatrix;
51 template <typename number>
52 class BlockSparseMatrix;
53
54 namespace internal
55 {
56 namespace AffineConstraints
57 {
58 using size_type = types::global_dof_index;
59
60 /**
61 * This struct contains all the information we need to store about each of
62 * the global entries (global_row): are they obtained directly by some local
63 * entry (local_row) or some constraints (constraint_position). This is not
64 * directly used in the user code, but accessed via the GlobalRowsFromLocal.
65 *
66 * The actions performed here correspond to reshaping the constraint
67 * information from global degrees of freedom to local ones (i.e.,
68 * cell-related DoFs), and also transforming the constraint information from
69 * compressed row storage (each local dof that is constrained has a list of
70 * constraint entries associated to it) into compressed column storage based
71 * on the cell-related DoFs (we have a list of global degrees of freedom,
72 * and to each we have a list of local rows where the entries come from). To
73 * increase the speed, we additionally store whether an entry is generated
74 * directly from the local degrees of freedom or whether it comes from a
75 * constraint.
76 */
77 struct Distributing
78 {
79 Distributing(const size_type global_row = numbers::invalid_size_type,
80 const size_type local_row = numbers::invalid_size_type);
81
82 Distributing(const Distributing &in);
83
84 Distributing &
85 operator=(const Distributing &in);
86
87 bool
88 operator<(const Distributing &in) const
89 {
90 return global_row < in.global_row;
91 }
92
93 size_type global_row;
94 size_type local_row;
95 mutable size_type constraint_position;
96 };
97
98
99
100 /**
101 * This class represents a cache for constraints that are encountered on a
102 * local level. The functionality is similar to
103 * std::vector<std::vector<std::pair<uint,double> > >, but tuned so that
104 * frequent memory allocation for each entry is avoided. The data is put
105 * into a std::vector<std::pair<uint,double> > and the row length is kept
106 * fixed at row_length. Both the number of rows and the row length can
107 * change is this structure is filled. In that case, the data is
108 * rearranged. This is not directly used in the user code, but accessed
109 * via the GlobalRowsFromLocal.
110 */
111 template <typename number>
112 struct DataCache
113 {
114 DataCache();
115
116 void
117 reinit();
118
119 size_type
120 insert_new_index(const std::pair<size_type, number> &pair);
121
122 void
123 append_index(const size_type index,
124 const std::pair<size_type, number> &pair);
125
126 size_type
127 get_size(const size_type index) const;
128
129 const std::pair<size_type, number> *
130 get_entry(const size_type index) const;
131
132 size_type row_length;
133
134 std::vector<std::pair<size_type, number>> data;
135
136 std::vector<size_type> individual_size;
137 };
138
139
140
141 /**
142 * A data structure that collects all the global rows from a local
143 * contribution (cell) and their origin (direct/constraint). This
144 * is basically a vector consisting of "Distributing" structs
145 * using access via the DataCache. The structure provides some
146 * specialized sort and insert functions.
147 *
148 * In case there are no constraints, this is basically a list of pairs
149 * `<uint,uint>` with the first index being the global index and the second
150 * index the local index. The list is sorted with respect to the global
151 * index.
152 *
153 * In case there are constraints, a global dof might get a contribution also
154 * because it gets data from a constrained dof. This means that a global dof
155 * might also have indirect contributions from a local dof via a constraint,
156 * besides the direct ones.
157 *
158 * The actions performed here correspond to reshaping the constraint
159 * information from global degrees of freedom to local ones (i.e.,
160 * cell-related DoFs), and also transforming the constraint information from
161 * compressed row storage (each local dof that is constrained has a list of
162 * constraint entries associated to it) into compressed column storage based
163 * on the cell-related DoFs (we have a list of global degrees of freedom,
164 * and to each we have a list of local rows where the entries come from). To
165 * increase the speed, we additionally store whether an entry is generated
166 * directly from the local degrees of freedom or whether it comes from a
167 * constraint.
168 */
169 template <typename number>
170 class GlobalRowsFromLocal
171 {
172 public:
173 /**
174 * Constructor.
175 */
176 GlobalRowsFromLocal();
177
178 void
179 reinit(const size_type n_local_rows);
180
181 void
182 insert_index(const size_type global_row,
183 const size_type local_row,
184 const number constraint_value);
185 void
186 sort();
187
188 void
189 print(std::ostream &os);
190
191 /**
192 * Return the number of global indices in the struct.
193 */
194 size_type
195 size() const;
196
197 /**
198 * Return the number of constraints that are associated to the
199 * counter_index-th entry in the list.
200 */
201 size_type
202 size(const size_type counter_index) const;
203
204 /**
205 * Return the global row of the counter_index-th entry in the list.
206 */
207 size_type
208 global_row(const size_type counter_index) const;
209
210 /**
211 * Return the global row of the counter_index-th entry in the list.
212 */
213 size_type &
214 global_row(const size_type counter_index);
215
216 /**
217 * Return the local row in the cell matrix associated with the
218 * counter_index-th entry in the list. Return invalid_size_type for
219 * constrained rows.
220 */
221 size_type
222 local_row(const size_type counter_index) const;
223
224 /**
225 * Return a reference instead of the value as in the function above.
226 */
227 size_type &
228 local_row(const size_type counter_index);
229
230 /**
231 * Return the local row in the cell matrix associated with the
232 * counter_index-th entry in the list in the index_in_constraint-th
233 * position of constraints.
234 */
235 size_type
236 local_row(const size_type counter_index,
237 const size_type index_in_constraint) const;
238
239 /**
240 * Return the value of the constraint in the counter_index-th entry in
241 * the list in the index_in_constraint-th position of constraints.
242 */
243 number
244 constraint_value(const size_type counter_index,
245 const size_type index_in_constraint) const;
246
247 /**
248 * Return whether this object stores a constraint in which one degree
249 * of freedom is constrained against another degree of freedom (as
250 * opposed to having only constraints of the form $x_i=42$ where
251 * no other degree of freedom appears on the right side).
252 */
253 bool
254 have_indirect_rows() const;
255
256 /**
257 * Append an entry that is constrained. This means that there is one less
258 * nontrivial row.
259 */
260 void
261 insert_constraint(const size_type constrained_local_dof);
262
263 /**
264 * Return the number of degrees of freedom for which this object
265 * stores constraints. Note that this is the number of degrees
266 * of freedom for which the *current* MPI process stores
267 * constraints, not the total number of constrained degrees of
268 * freedom across all processes.
269 */
270 size_type
271 n_constraints() const;
272
273 /**
274 * Return the number of constrained dofs in the structure that have an
275 * inhomogeneity.
276 */
277 size_type
278 n_inhomogeneities() const;
279
280 /**
281 * This function tells the structure that the ith constraint is
282 * inhomogeneous. inhomogeneous constraints contribute to right hand
283 * sides, so to have fast access to them, put them before homogeneous
284 * constraints.
285 */
286 void
287 set_ith_constraint_inhomogeneous(const size_type i);
288
289 /**
290 * The local row where constraint number i was detected, to find that row
291 * easily when the GlobalRowsToLocal has been set up.
292 */
293 size_type
294 constraint_origin(size_type i) const;
295
296 /**
297 * A vector that contains all the global ids and the corresponding local
298 * ids as well as a pointer to that data where we store how to resolve
299 * constraints.
300 */
301 std::vector<Distributing> total_row_indices;
302
303 private:
304 /**
305 * A data structure that holds the actual data from the constraints.
306 */
307 DataCache<number> data_cache;
308
309 /**
310 * A number that states how many rows there are, constraints
311 * disregarded.
312 */
313 size_type n_active_rows;
314
315 /**
316 * A number that represents the number of rows with
317 * inhomogeneous constraints.
318 */
319 size_type n_inhomogeneous_rows;
320 };
321
322
323
324 /**
325 * Scratch data that is used during calls to distribute_local_to_global and
326 * add_entries_local_to_global. In order to avoid frequent memory
327 * allocation, we keep the data alive from one call to the next in a static
328 * variable. Since we want to allow for different number types in matrices,
329 * this is a template.
330 *
331 * Since each thread gets its private version of scratch data out of a
332 * ThreadLocalStorage, no conflicting access can occur. For this to be
333 * valid, we need to make sure that no call within
334 * distribute_local_to_global is made that by itself can spawn tasks.
335 * Otherwise, we might end up in a situation where several threads fight for
336 * the data.
337 *
338 * Access to the scratch data is only through an accessor class which
339 * handles the access as well as marks the data as used.
340 */
341 template <typename number>
342 struct ScratchData
343 {
344 /**
345 * Constructor, does nothing.
346 */
347 ScratchData()
348 : in_use(false)
349 {}
350
351 /**
352 * Copy constructor, does nothing
353 */
354 ScratchData(const ScratchData &)
355 : in_use(false)
356 {}
357
358 /**
359 * Stores whether the data is currently in use.
360 */
361 bool in_use;
362
363 /**
364 * Temporary array for pairs of indices
365 */
366 std::vector<std::pair<size_type, size_type>> new_entries;
367
368 /**
369 * Temporary array for row indices
370 */
371 std::vector<size_type> rows;
372
373 /**
374 * Temporary array for column indices
375 */
376 std::vector<size_type> columns;
377
378 /**
379 * Temporary array for column values
380 */
381 std::vector<number> values;
382
383 /**
384 * Temporary array for block start indices
385 */
386 std::vector<size_type> block_starts;
387
388 /**
389 * Temporary array for vector indices
390 */
391 std::vector<size_type> vector_indices;
392
393 /**
394 * Temporary array for vector values
395 */
396 std::vector<number> vector_values;
397
398 /**
399 * Data array for reorder row/column indices.
400 */
401 GlobalRowsFromLocal<number> global_rows;
402
403 /**
404 * Data array for reorder row/column indices.
405 */
406 GlobalRowsFromLocal<number> global_columns;
407 };
408 } // namespace AffineConstraints
409 } // namespace internal
410
411 namespace internal
412 {
413 namespace AffineConstraintsImplementation
414 {
415 template <typename VectorType>
416 void
417 set_zero_all(const std::vector<types::global_dof_index> &cm,
418 VectorType &vec);
419
420 template <class T>
421 void
422 set_zero_all(const std::vector<types::global_dof_index> &cm,
423 dealii::Vector<T> &vec);
424
425 template <class T>
426 void
427 set_zero_all(const std::vector<types::global_dof_index> &cm,
428 dealii::BlockVector<T> &vec);
429 } // namespace AffineConstraintsImplementation
430 } // namespace internal
431 #endif
432
433
434
435 /**
436 * This class implements dealing with linear (possibly inhomogeneous)
437 * constraints on degrees of freedom. The concept and origin of such
438 * constraints is extensively described in the
439 * @ref constraints
440 * topic. The class is meant to deal with a limited number of constraints
441 * relative to the total number of degrees of freedom, for example a few per
442 * cent up to maybe 30 per cent; and with a linear combination of <i>M</i>
443 * other degrees of freedom where <i>M</i> is also relatively small (no larger
444 * than at most around the average number of entries per row of a linear
445 * system). It is <em>not</em> meant to describe full rank linear systems.
446 *
447 * The algorithms used in the implementation of this class are described in
448 * some detail in the
449 * @ref hp_paper "hp-paper".
450 * There is also a significant amount of documentation on how to use this
451 * class in the
452 * @ref constraints
453 * topic.
454 *
455 *
456 * <h3>Description of constraints</h3>
457 *
458 * Each "line" in objects of this class corresponds to one constrained degree
459 * of freedom, with the number of the line being <i>i</i>, entered by using
460 * add_line() or add_lines(). The entries in this line are pairs of the form
461 * (<i>j</i>,<i>a<sub>ij</sub></i>), which are added by add_entry() or
462 * add_entries(). The organization is essentially a SparsityPattern, but with
463 * only a few lines containing nonzero elements, and therefore no data wasted
464 * on the others. For each line, which has been added by the mechanism above,
465 * an elimination of the constrained degree of freedom of the form
466 * @f[
467 * x_i = \sum_j a_{ij} x_j + b_i
468 * @f]
469 * is performed, where <i>b<sub>i</sub></i> is optional and set by
470 * set_inhomogeneity(). Thus, if a constraint is formulated for instance as a
471 * zero mean value of several degrees of freedom, one of the degrees has to be
472 * chosen to be eliminated.
473 *
474 * Note that the constraints are linear in the <i>x<sub>i</sub></i>, and that
475 * there might be a constant (non-homogeneous) term in the constraint. This is
476 * exactly the form we need for hanging node constraints, where we need to
477 * constrain one degree of freedom in terms of others. There are other
478 * conditions of this form possible, for example for implementing mean value
479 * conditions as is done in the step-11 tutorial program. The name of the
480 * class stems from the fact that these constraints can be represented in
481 * matrix form as <b>X</b> <i>x</i> = <i>b</i>, and this object then describes
482 * the matrix <b>X</b> and the vector <i>b</i>. The most frequent way to
483 * create/fill objects of this type is using the
484 * DoFTools::make_hanging_node_constraints() function. The use of these
485 * objects is first explained in step-6.
486 *
487 * Objects of the present type are organized in lines (rows), but only those
488 * lines are stored where constraints are present. New constraints are added
489 * by adding new lines using the add_line() function, and then populating it
490 * using the add_entry() function to a given line, or add_entries() to add
491 * more than one entry at a time. The right hand side element, if nonzero, can
492 * be set using the set_inhomogeneity() function. After all constraints have
493 * been added, you need to call close(), which compresses the storage format
494 * and sorts the entries.
495 *
496 * @note Many of the algorithms this class implements are discussed in the
497 * @ref hp_paper.
498 * The algorithms are also related to those shown in @cite Shephard1984 ,
499 * with the difference that the algorithms shown there
500 * completely eliminate constrained degrees of freedom, whereas we usually
501 * keep them as part of the linear system (but zero out the row and column
502 * to decouple this degree of freedom from the rest of the linear system).
503 *
504 * @ingroup dofs
505 * @ingroup constraints
506 */
507 template <typename number = double>
508 class AffineConstraints : public EnableObserverPointer
509 {
510 public:
511 /**
512 * Declare the type for container size.
513 */
514 using size_type = types::global_dof_index;
515
516 /**
517 * An enum that describes what should happen if the two AffineConstraints
518 * objects involved in a call to the merge() function happen to have
519 * constraints on the same degrees of freedom.
520 */
521 enum MergeConflictBehavior
522 {
523 /**
524 * Throw an exception if the two objects concerned have conflicting
525 * constraints on the same degree of freedom.
526 */
527 no_conflicts_allowed,
528
529 /**
530 * In an operation <code>cm1.merge(cm2)</code>, if <code>cm1</code> and
531 * <code>cm2</code> have constraints on the same degree of freedom, take
532 * the one from <code>cm1</code>.
533 */
534 left_object_wins,
535
536 /**
537 * In an operation <code>cm1.merge(cm2)</code>, if <code>cm1</code> and
538 * <code>cm2</code> have constraints on the same degree of freedom, take
539 * the one from <code>cm2</code>.
540 */
541 right_object_wins
542 };
543
544 /**
545 * Default constructor.
546 *
547 * This constructor sets up an object that stores all constraints eventually
548 * given to it. (This is in contrast to the following constructor that
549 * restricts which degrees of freedom we should care about -- for example,
550 * in a parallel context one would typically only store constraints
551 * for the locally relevant DoFs, see
552 * @ref GlossLocallyRelevantDof .)
553 * Consequently, this constructor creates internal data structures for
554 * <i>all</i> possible indices, leading to memory consumption on every
555 * processor that is proportional to the <i>overall</i> size of the
556 * problem, not just proportional to the size of the portion of the
557 * overall problem that is handled by the current processor. Calling
558 * this constructor in a parallel program is a common bug: Call the
559 * other one, with an index set, instead.
560 */
561 AffineConstraints();
562
563 /**
564 * Constructor. The supplied IndexSet defines for which indices
565 * this object will store constraints. In a calculation
566 * with a DoFHandler object based on parallel::distributed::Triangulation
567 * or parallel::shared::Triangulation, one should use the set of locally
568 * relevant DoFs (see
569 * @ref GlossLocallyRelevantDof).
570 *
571 * The given IndexSet allows the AffineConstraints container to save
572 * memory by just not caring about degrees of freedom that are not of
573 * importance to the current processor. In contrast, in parallel
574 * computations, if you do not provide such an index set (here, or
575 * using the reinit() function that takes such an argument), the
576 * current object will allocate memory proportional to the *total*
577 * number of degrees of freedom (accumulated over all processes),
578 * which is clearly wasteful and not efficient -- and should be considered
579 * a bug.
580 *
581 * @deprecated This constructor is equivalent to calling the following one with
582 * both of its arguments equal to the index set provided here. This
583 * is not wrong, but inefficient. Use the following constructor instead.
584 */
585 DEAL_II_DEPRECATED_WITH_COMMENT(
586 "Use the constructor with two index set arguments.")
587 explicit AffineConstraints(const IndexSet &locally_stored_constraints);
588
589 /**
590 * Constructor. The supplied IndexSet objects define which of the indices
591 * the object may encounter are locally owned, and for which indices
592 * this object will store constraints. In a calculation
593 * with a DoFHandler object based on parallel::distributed::Triangulation
594 * or parallel::shared::Triangulation, the first of these arguments
595 * should be the set of locally owned indices (see
596 * @ref GlossLocallyOwnedDof)
597 * and the second argument should use the set of locally
598 * relevant DoFs (see
599 * @ref GlossLocallyRelevantDof).
600 *
601 * The @p locally_owned_dofs argument indicates which elements of
602 * vectors that will be passed to the member functions of this
603 * object are locally owned (which is generally equal to the set of
604 * locally owned degrees of freedom -- thus the name of the
605 * argument). Knowledge of this set makes it possible to up front,
606 * in close(), determine which vector elements need to be imported
607 * when you later call the distribute() or related functions.
608 *
609 * The @p locally_stored_constraints IndexSet allows the AffineConstraints
610 * container to save memory by just not caring about degrees of freedom
611 * that are not of importance to the current processor. In contrast,
612 * in parallel computations, if you do not provide such an index set
613 * (here, or using the reinit() function that takes such an argument), the
614 * current object will allocate memory proportional to the *total*
615 * number of degrees of freedom (accumulated over all processes),
616 * which is clearly wasteful and not efficient -- and should be considered
617 * a bug. As mentioned above, one typically wants to provide the set of
618 * locally relevant degrees of freedom for this argument.
619 */
620 AffineConstraints(const IndexSet &locally_owned_dofs,
621 const IndexSet &locally_stored_constraints);
622
623 /**
624 * Copy constructor
625 */
626 explicit AffineConstraints(const AffineConstraints &affine_constraints);
627
628 /**
629 * Move constructor
630 */
631 AffineConstraints(AffineConstraints &&affine_constraints) noexcept =
632 default; // NOLINT
633
634 /**
635 * Copy operator. Like for many other large objects, this operator
636 * is deleted to avoid its inadvertent use in places such as
637 * accidentally declaring a @p AffineConstraints object as a
638 * function argument by value, rather than by reference.
639 *
640 * However, you can use the copy_from() function to explicitly
641 * copy AffineConstraints objects.
642 */
643 AffineConstraints &
644 operator=(const AffineConstraints &) = delete;
645
646 /**
647 * Move assignment operator
648 */
649 AffineConstraints &
650 operator=(AffineConstraints &&affine_constraints) noexcept =
651 default; // NOLINT
652
653 /**
654 * Copy the given object to the current one.
655 *
656 * This function exists because @p operator=() is explicitly
657 * disabled.
658 */
659 template <typename other_number>
660 void
661 copy_from(const AffineConstraints<other_number> &other);
662
663 /**
664 * Reset the AffineConstraints object. This results in an object that
665 * is as if it had been default-constructed. See the discussion in the
666 * documentation of the various constructors of this class for whether
667 * this is what you want -- in particular, for parallel computations,
668 * you do not want to call this function, but rather one of the other
669 * reinit() functions that take index sets.
670 */
671 void
672 reinit();
673
674 /**
675 * clear() the AffineConstraints object and supply an IndexSet that describes
676 * for which degrees of freedom this object can store constraints. See
677 * the discussion in the documentation of the constructor of this class
678 * that takes a single index set as argument.
679 *
680 * @deprecated Use the reinit() function with two index set arguments instead.
681 */
682 DEAL_II_DEPRECATED_WITH_COMMENT(
683 "Use the reinit() function with two index set arguments.")
684 void
685 reinit(const IndexSet &locally_stored_constraints);
686
687 /**
688 * clear() the AffineConstraints object and supply both an IndexSet
689 * object that describes which degrees of freedom the current process
690 * owns, and an IndexSet that describes
691 * for which degrees of freedom this object can store constraints. See
692 * the discussion in the documentation of the constructor of this class
693 * that takes two index sets as argument for more information.
694 */
695 void
696 reinit(const IndexSet &locally_owned_dofs,
697 const IndexSet &locally_stored_constraints);
698
699 /**
700 * Determines if we can store a constraint for the given @p line_n. This
701 * routine only matters in the distributed case and checks if the IndexSet
702 * provided to the constructor or reinit() function that determines
703 * which constraints to store, allows storage of the line provides
704 * as argument to this function. As a consequence, it will always return
705 * true if not in the distributed case.
706 */
707 bool
708 can_store_line(const size_type line_n) const;
709
710 /**
711 * Return the index set describing which part of the degrees of freedom to
712 * which this object stores constraints are "locally owned". Typically,
713 * these would be the
714 * @ref GlossLocallyOwnedDof "locally owned degrees of freedom".
715 * This function returns the corresponding index set provided to either
716 * the constructor or the reinit() function of this class.
717 */
718 const IndexSet &
719 get_locally_owned_indices() const;
720
721 /**
722 * Return the index set describing locally relevant lines if any are
723 * present. Note that if no local lines were given, this represents an empty
724 * IndexSet, whereas otherwise it contains the global problem size and the
725 * local range.
726 */
727 const IndexSet &
728 get_local_lines() const;
729
730 /**
731 * This function copies the content of @p constraints_in with DoFs that are
732 * element of the IndexSet @p filter. Elements that are not present in the
733 * IndexSet are ignored. All DoFs will be transformed to local index space
734 * of the filter, both the constrained DoFs and the other DoFs these entries
735 * are constrained to. The local index space of the filter is a contiguous
736 * numbering of all (global) DoFs that are elements in the filter.
737 *
738 * If, for example, the filter represents the range <tt>[10,20)</tt>, and
739 * the constraints object @p constraints_in includes the global indices
740 * <tt>{7,13,14}</tt>, the indices <tt>{3,4}</tt> are added to the calling
741 * constraints object (since 13 and 14 are elements in the filter and element
742 * 13 is the fourth element in the index, and 14 is the fifth).
743 *
744 * This function provides an easy way to create a AffineConstraints for
745 * certain vector components in a vector-valued problem from a full
746 * AffineConstraints, i.e. extracting a diagonal subblock from a larger
747 * AffineConstraints. The block is specified by the IndexSet argument.
748 *
749 * @deprecated This function is a combination of the get_view() function
750 * and merge() in that it selects a subset of constraints from another
751 * constraints object that is then merged into the current one. But
752 * the current function does not deal well with index sets. Furthermore,
753 * it simply discards parts of constraints that constrain one degree
754 * of freedom against ones that are not selected in the filter -- something
755 * that should probably be considered a bug. Use get_view() and merge()
756 * instead.
757 */
758 DEAL_II_DEPRECATED_WITH_COMMENT("Use get_view() and merge() instead.")
759 void
760 add_selected_constraints(const AffineConstraints &constraints_in,
761 const IndexSet &filter);
762
763 /**
764 * @name Adding constraints
765 * @{
766 */
767
768 /**
769 * Add a constraint to this object. This function adds a constraint
770 * of the form
771 * @f[
772 * x_i = \sum_{j=1}^n w_j x_{k_j} + b
773 * @f]
774 * where $i$ is the number of the degree of freedom to be constrained
775 * and is provided by the @p constrained_dofs argument. The weights
776 * $w_j$ and indices $k_j$ are provided as pairs in the
777 * @p dependencies argument, and the inhomogeneity $b$ is
778 * provided by the last argument.
779 *
780 * As an example, if you want to add the constraint
781 * @f[
782 * x_{42} = 0.5 x_{12} + 0.5 x_{36} + 27
783 * @f]
784 * you would call this function as follows:
785 * @code
786 * constraints.add_constraint (42, {{12, 0.5}, {36, 0.5}}, 27.0);
787 * @endcode
788 * On the other hand, if (as one often wants to) you need a constraint
789 * of the kind
790 * @f[
791 * x_{42} = 27
792 * @f]
793 * you would call this function as follows:
794 * @code
795 * constraints.add_constraint (42, {}, 27.0);
796 * @endcode
797 * If you want to constrain a degree of freedom to zero, i.e.,
798 * require that
799 * @f[
800 * x_{42} = 0
801 * @f]
802 * you would call this function as follows:
803 * @code
804 * constraints.add_constraint (42, {}, 0.0);
805 * @endcode
806 * That said, this special case can be achieved in a more obvious way by
807 * calling
808 * @code
809 * constraints.constrain_dof_to_zero (42);
810 * @endcode
811 * instead.
812 */
813 void
814 add_constraint(
815 const size_type constrained_dof,
816 const ArrayView<const std::pair<size_type, number>> &dependencies,
817 const number inhomogeneity = 0);
818
819 /**
820 * Constrain the given degree of freedom to be zero, i.e.,
821 * require a constraint like
822 * @f[
823 * x_{42} = 0.
824 * @f]
825 * Calling this function is equivalent to, but more readable than, saying
826 * @code
827 * constraints.add_constraint (42, {}, 0.0);
828 * @endcode
829 *
830 * It is not an error to call this function more than once on the same
831 * degree of freedom, but it is an error to call this function on a
832 * degree of freedom that has previously been constrained to either
833 * a different value than zero, or to a linear combination of degrees
834 * of freedom via the add_constraint() function.
835 */
836 void
837 constrain_dof_to_zero(const size_type constrained_dof);
838
839 /**
840 * Add a new line to the matrix. If the line already exists, then the
841 * function simply returns without doing anything.
842 */
843 void
844 add_line(const size_type line_n);
845
846 /**
847 * Call the first add_line() function for every index <code>i</code> for
848 * which <code>lines[i]</code> is true.
849 *
850 * This function essentially exists to allow adding several constraints of
851 * the form <i>x<sub>i</sub></i>=0 all at once, where the set of indices
852 * <i>i</i> for which these constraints should be added are given by the
853 * argument of this function. On the other hand, just as if the
854 * single-argument add_line() function were called repeatedly, the constraints
855 * can later be modified to include linear dependencies using the add_entry()
856 * function as well as inhomogeneities using set_inhomogeneity().
857 */
858 void
859 add_lines(const std::vector<bool> &lines);
860
861 /**
862 * Call the first add_line() function for every index <code>i</code> that
863 * appears in the argument.
864 *
865 * This function essentially exists to allow adding several constraints of
866 * the form <i>x<sub>i</sub></i>=0 all at once, where the set of indices
867 * <i>i</i> for which these constraints should be added are given by the
868 * argument of this function. On the other hand, just as if the
869 * single-argument add_line() function were called repeatedly, the constraints
870 * can later be modified to include linear dependencies using the add_entry()
871 * function as well as inhomogeneities using set_inhomogeneity().
872 */
873 void
874 add_lines(const std::set<size_type> &lines);
875
876 /**
877 * Call the first add_line() function for every index <code>i</code> that
878 * appears in the argument.
879 *
880 * This function essentially exists to allow adding several constraints of
881 * the form <i>x<sub>i</sub></i>=0 all at once, where the set of indices
882 * <i>i</i> for which these constraints should be added are given by the
883 * argument of this function. On the other hand, just as if the
884 * single-argument add_line() function were called repeatedly, the constraints
885 * can later be modified to include linear dependencies using the add_entry()
886 * function as well as inhomogeneities using set_inhomogeneity().
887 */
888 void
889 add_lines(const IndexSet &lines);
890
891 /**
892 * Add an entry to a given line. In other words, this function adds
893 * a term $a_{ij} x_j$ to the constraints for the $i$th degree of freedom.
894 *
895 * If an entry with the same indices as the one this function call denotes
896 * already exists, then this function simply returns provided that the value
897 * of the entry is the same. Thus, it does no harm to enter a constraint
898 * twice.
899 *
900 * @param[in] constrained_dof_index The index $i$ of the degree of freedom
901 * that is being constrained.
902 * @param[in] column The index $j$ of the degree of freedom being entered
903 * into the constraint for degree of freedom $i$.
904 * @param[in] weight The factor $a_{ij}$ that multiplies $x_j$.
905 */
906 void
907 add_entry(const size_type constrained_dof_index,
908 const size_type column,
909 const number weight);
910
911 /**
912 * Add a whole series of entries, denoted by pairs of column indices and
913 * weight values, to a line of constraints. This function is equivalent to
914 * calling the preceding function several times, but is faster.
915 */
916 void
917 add_entries(
918 const size_type constrained_dof_index,
919 const std::vector<std::pair<size_type, number>> &col_weight_pairs);
920
921 /**
922 * Set an inhomogeneity to the constraint for a degree of freedom. In other
923 * words, it adds a constant $b_i$ to the constraint for degree of freedom
924 * $i$. For this to work, you need to call add_line() first for the given
925 * degree of freedom.
926 *
927 * @param[in] constrained_dof_index The index $i$ of the degree of freedom
928 * that is being constrained.
929 * @param[in] value The right hand side value $b_i$ for the constraint on
930 * the degree of freedom $i$.
931 */
932 void
933 set_inhomogeneity(const size_type constrained_dof_index, const number value);
934
935 /**
936 * Close the filling of entries. Since the lines of a matrix of this type
937 * are usually filled in an arbitrary order and since we do not want to use
938 * associative constrainers to store the lines, we need to sort the lines
939 * and within the lines the columns before usage of the matrix. This is done
940 * through this function.
941 *
942 * Also, zero entries are discarded, since they are not needed.
943 *
944 * After closing, no more entries are accepted. If the object was already
945 * closed, then this function returns immediately.
946 *
947 * This function also resolves chains of constraints. For example, degree of
948 * freedom 13 may be constrained to $u_{13} = \frac{u_3}{2} + \frac{u_7}{2}$
949 * while degree of freedom 7 is itself constrained as $u_{7} = \frac{u_2}{2}
950 * + \frac{u_4}{2}$. Then, the resolution will be that $u_{13} =
951 * \frac{u_3}{2} + \frac{u_2}{4} + \frac{u_4}{4}$. Note, however, that
952 * cycles in this graph of constraints are not allowed, i.e., for example
953 * $u_4$ may not itself be constrained, directly or indirectly, to $u_{13}$
954 * again.
955 */
956 void
957 close();
958
959 /**
960 * Check if the function close() was called or there are no
961 * constraints locally, which is normally the case if a dummy
962 * AffineConstraints was created for the DG case.
963 */
964 bool
965 is_closed() const;
966
967 /**
968 * Check if the function close() was called or there are no
969 * constraints globally, which is normally the case if a dummy
970 * AffineConstraints was created for the DG case.
971 */
972 bool
973 is_closed(const MPI_Comm comm) const;
974
975 /**
976 * Merge the constraints represented by the object given as argument into
977 * the constraints represented by this object. Both objects may or may not
978 * be closed (by having their function close() called before). If this
979 * object was closed before, then it will be closed afterwards as well.
980 * Note, however, that if the other argument is closed, then merging may be
981 * significantly faster.
982 *
983 * Using the default value of the second arguments, the constraints in each
984 * of the two objects (the old one represented by this object and the
985 * argument) may not refer to the same degree of freedom, i.e. a degree of
986 * freedom that is constrained in one object may not be constrained in the
987 * second. If this is nevertheless the case, an exception is thrown.
988 * However, this behavior can be changed by providing a different value for
989 * the second argument.
990 *
991 * By default, merging two AffineConstraints objects that are initialized
992 * with different IndexSet objects is not allowed.
993 * This behavior can be altered by setting @p allow_different_local_lines
994 * appropriately.
995 *
996 * Merging an AffineConstraints that is initialized with an IndexSet
997 * and one that is not initialized with an IndexSet is not implemented.
998 */
999 template <typename other_number>
1000 void
1001 merge(
1002 const AffineConstraints<other_number> &other_constraints,
1003 const MergeConflictBehavior merge_conflict_behavior = no_conflicts_allowed,
1004 const bool allow_different_local_lines = false);
1005
1006 /**
1007 * Shift all entries of this matrix down @p offset rows and over @p offset
1008 * columns. If this object is initialized with an IndexSet, local_lines are
1009 * shifted as well.
1010 *
1011 * This function is useful if you are building block matrices, where all
1012 * blocks are built by the same DoFHandler object, i.e. the matrix size is
1013 * larger than the number of degrees of freedom. Since several matrix rows
1014 * and columns correspond to the same degrees of freedom, you'd generate
1015 * several constraint objects, then shift them, and finally merge() them
1016 * together again.
1017 */
1018 void
1019 shift(const size_type offset);
1020
1021 /**
1022 * This function provides a "view" into a constraint
1023 * object. Specifically, given a "mask" index set that describes
1024 * which constraints we are interested in, it returns an
1025 * AffineConstraints object that contains only those constraints
1026 * that correspond to degrees of freedom that are listed in the
1027 * mask, with indices shifted so that they correspond to the
1028 * position within the mask. This process is the same as how
1029 * IndexSet::get_view() computes the shifted indices. The function
1030 * is typically used to extract from an AffineConstraints object
1031 * corresponding to a DoFHandler only those constraints that
1032 * correspond to a specific variable (say, to the velocity in a
1033 * Stokes system) so that the resulting AffineConstraints object can
1034 * be applied to a single block of a block vector of solutions; in
1035 * this case, the mask would be the index set of velocity degrees of
1036 * freedom, as a subset of all degrees of freedom.
1037 *
1038 * This function can only work if the degrees of freedom selected by
1039 * the mask are constrained only against other degrees of freedom
1040 * that are listed in the mask. In the example above, this means
1041 * that constraints for the selected velocity degrees of freedom are
1042 * only against other velocity degrees of freedom, but not against
1043 * any pressure degrees of freedom. If that is not so, an assertion
1044 * will be triggered.
1045 *
1046 * A typical case where this function is useful is as follows. Say,
1047 * you have a block linear system in which you have blocks
1048 * corresponding to variables $(u,p,T,c)$ (which you can think of as
1049 * velocity, pressure, temperature, and chemical composition -- or
1050 * whatever other kind of problem you are currently considering in
1051 * your own work). Let's assume we have developed a linear solver or
1052 * preconditioner that first solves the coupled $u$-$T$ system, and
1053 * once that is done, solves the $p$-$c$ system. In this case, it is
1054 * often useful to set up block vectors with only two components
1055 * corresponding to the $u$ and $T$ components, and later for only
1056 * the $p$-$c$ components of the solution. As part of this, you will
1057 * want to apply constraints (using the distribute() function of this
1058 * class) to only the 2-block vector, but for this you need to obtain
1059 * an AffineConstraints object that represents only those constraints
1060 * that correspond to the variables in question, and in the order
1061 * in which they appear in the 2-block vector rather than in global
1062 * 4-block vectors. This function allows you to extract such an
1063 * object corresponding to a subset of constraints by applying a mask
1064 * to the global constraints object that corresponds to the
1065 * variables we're currently interested in. For the $u$-$T$ system,
1066 * we need a mask that contains all indices of $u$ degrees of
1067 * freedom as well as all indices of $T$ degrees of freedom.
1068 */
1069 AffineConstraints
1070 get_view(const IndexSet &mask) const;
1071
1072 /**
1073 * Clear all entries of this matrix. Reset the flag determining whether new
1074 * entries are accepted or not.
1075 *
1076 * This function may be called also on objects which are empty or already
1077 * cleared.
1078 */
1079 void
1080 clear();
1081
1082 /**
1083 * @}
1084 */
1085
1086 /**
1087 * @name Querying constraints
1088 * @{
1089 */
1090
1091 /**
1092 * Return number of constraints stored in this matrix.
1093 */
1094 size_type
1095 n_constraints() const;
1096
1097 /**
1098 * Return number of constraints stored in this matrix that are identities,
1099 * i.e., those constraints with only one degree of freedom and weight one.
1100 */
1101 size_type
1102 n_identities() const;
1103
1104 /**
1105 * Return number of constraints stored in this matrix that have an
1106 * inhomogenity, i.e., those constraints with a non-trivial inhomogeneous
1107 * value.
1108 */
1109 size_type
1110 n_inhomogeneities() const;
1111
1112 /**
1113 * Return whether the degree of freedom with number @p line_n is a
1114 * constrained one.
1115 *
1116 * Note that if close() was called before, then this function is
1117 * significantly faster, since then the constrained degrees of freedom are
1118 * sorted and we can do a binary search, while before close() was called, we
1119 * have to perform a linear search through all entries.
1120 */
1121 bool
1122 is_constrained(const size_type line_n) const;
1123
1124 /**
1125 * Return whether the dof is constrained, and whether it is constrained to
1126 * only one other degree of freedom with weight one. The function therefore
1127 * returns whether the degree of freedom would simply be eliminated in favor
1128 * of exactly one other degree of freedom.
1129 *
1130 * The function returns @p false if either the degree of freedom is not
1131 * constrained at all, or if it is constrained to more than one other degree
1132 * of freedom, or if it is constrained to only one degree of freedom but
1133 * with a weight different from one.
1134 */
1135 bool
1136 is_identity_constrained(const size_type line_n) const;
1137
1138 /**
1139 * Return whether the two given degrees of freedom are linked by an equality
1140 * constraint that either constrains index1 to be so that
1141 * <code>index1=index2</code> or constrains index2 so that
1142 * <code>index2=index1</code>.
1143 */
1144 bool
1145 are_identity_constrained(const size_type line_n_1,
1146 const size_type line_n_2) const;
1147
1148 /**
1149 * Return the maximum number of other dofs that one dof is constrained to.
1150 * For example, in 2d a hanging node is constrained only to its two
1151 * neighbors, so the returned value would be 2. However, for higher order
1152 * elements and/or higher dimensions, or other types of constraints, this
1153 * number is no more obvious.
1154 *
1155 * The name indicates that within the system matrix, references to a
1156 * constrained node are indirected to the nodes it is constrained to.
1157 */
1158 size_type
1159 max_constraint_indirections() const;
1160
1161 /**
1162 * Return <tt>true</tt> in case the dof is constrained and there is a
1163 * non-trivial inhomogeneous values set to the dof.
1164 */
1165 bool
1166 is_inhomogeneously_constrained(const size_type index) const;
1167
1168 /**
1169 * Return <tt>false</tt> if all constraints in the AffineConstraints are
1170 * homogeneous ones, and <tt>true</tt> if there is at least one
1171 * inhomogeneity.
1172 */
1173 bool
1174 has_inhomogeneities() const;
1175
1176 /**
1177 * Return a pointer to the vector of entries if a line is constrained,
1178 * and a zero pointer in case the dof is not constrained.
1179 */
1180 const std::vector<std::pair<size_type, number>> *
1181 get_constraint_entries(const size_type line_n) const;
1182
1183 /**
1184 * Return the value of the inhomogeneity stored in the constrained dof @p
1185 * line_n. Unconstrained dofs also return a zero value.
1186 */
1187 number
1188 get_inhomogeneity(const size_type line_n) const;
1189
1190 /**
1191 * Print the constraints represented by the current object to the
1192 * given stream.
1193 *
1194 * For each constraint of the form
1195 * @f[
1196 * x_{42} = 0.5 x_2 + 0.25 x_{14} + 2.75
1197 * @f]
1198 * this function will write a sequence of lines that look like this:
1199 * @code
1200 * 42 2 : 0.5
1201 * 42 14 : 0.25
1202 * 42 : 2.75
1203 * @endcode
1204 * The last line is only shown if the inhomogeneity (here: 2.75) is
1205 * nonzero.
1206 *
1207 * A block of lines such as the one above is repeated for each
1208 * constrained degree of freedom.
1209 */
1210 void
1211 print(std::ostream &out) const;
1212
1213 /**
1214 * Write the graph of constraints in 'dot' format. 'dot' is a program that
1215 * can take a list of nodes and produce a graphical representation of the
1216 * graph of constrained degrees of freedom and the degrees of freedom they
1217 * are constrained to.
1218 *
1219 * The output of this function can be used as input to the 'dot' program
1220 * that can convert the graph into a graphical representation in postscript,
1221 * png, xfig, and a number of other formats.
1222 *
1223 * This function exists mostly for debugging purposes.
1224 */
1225 void
1226 write_dot(std::ostream &) const;
1227
1228 /**
1229 * Determine an estimate for the memory consumption (in bytes) of this
1230 * object.
1231 */
1232 std::size_t
1233 memory_consumption() const;
1234
1235 /**
1236 * Add the constraint indices associated to the indices in the given vector.
1237 * After a call to this function, the indices vector contains the initial
1238 * elements and all the associated constrained indices. This function sorts
1239 * the elements and suppresses duplicates.
1240 */
1241 void
1242 resolve_indices(std::vector<types::global_dof_index> &indices) const;
1243
1244 /**
1245 * @}
1246 */
1247
1248 /**
1249 * @name Eliminating constraints from linear systems after their creation
1250 * @{
1251 */
1252
1253 /**
1254 * Condense a sparsity pattern. The name of the function mimics the name of
1255 * the function we use to condense linear systems, but it is a bit of a
1256 * misnomer for the current context. This is because in the context of
1257 * linear systems, we eliminate certain rows and columns of the linear
1258 * system, i.e., we "reduce" or "condense" the linear system. On the other
1259 * hand, in the current context, the functions does not remove nonzero
1260 * entries from the sparsity pattern. Rather, it adds those nonzero entry
1261 * locations to the sparsity pattern that will later be needed for the
1262 * process of condensation of constrained degrees of freedom from a linear
1263 * system.
1264 *
1265 * Since this function adds new nonzero entries to the sparsity pattern, the
1266 * given sparsity pattern must not be compressed. The current object must be
1267 * closed. The sparsity pattern is compressed at the end of the function.
1268 */
1269 void
1270 condense(SparsityPattern &sparsity) const;
1271
1272 /**
1273 * Same function as above, but condenses square block sparsity patterns.
1274 */
1275 void
1276 condense(BlockSparsityPattern &sparsity) const;
1277
1278 /**
1279 * Same function as above, but condenses square compressed sparsity
1280 * patterns.
1281 */
1282 void
1283 condense(DynamicSparsityPattern &sparsity) const;
1284
1285 /**
1286 * Same function as above, but condenses square compressed sparsity
1287 * patterns.
1288 */
1289 void
1290 condense(BlockDynamicSparsityPattern &sparsity) const;
1291
1292 /**
1293 * Condense a given matrix, i.e., eliminate the rows and columns of the
1294 * matrix that correspond to constrained degrees of freedom.
1295 *
1296 * See the general documentation of this class for more detailed
1297 * information.
1298 */
1299 void
1300 condense(SparseMatrix<number> &matrix) const;
1301
1302 /**
1303 * Same function as above, but condenses square block sparse matrices.
1304 */
1305 void
1306 condense(BlockSparseMatrix<number> &matrix) const;
1307
1308 /**
1309 * Condense the given vector in-place. The @p VectorType may be a
1310 * Vector<float>, Vector<number>, BlockVector<tt><...></tt>, a PETSc or
1311 * Trilinos vector wrapper class, or any other type having the same
1312 * interface. Note that this function does not take any inhomogeneity into
1313 * account and throws an exception in case there are any inhomogeneities.
1314 * Use the function using both a matrix and vector for that case.
1315 *
1316 * @note This function does not work for MPI vectors. Use condense() with
1317 * two vector arguments instead.
1318 */
1319 template <typename VectorType>
1320 void
1321 condense(VectorType &vec) const;
1322
1323 /**
1324 * The function copies and condenses values from @p vec_ghosted into @p
1325 * output. In a serial code it is equivalent to calling condense (vec). If
1326 * called in parallel, @p vec_ghosted is supposed to contain ghost elements
1327 * while @p output should not.
1328 */
1329 template <typename VectorType>
1330 void
1331 condense(const VectorType &vec_ghosted, VectorType &output) const;
1332
1333 /**
1334 * Condense a given matrix and a given vector by eliminating rows and
1335 * columns of the linear system that correspond to constrained degrees of
1336 * freedom. The sparsity pattern associated with the matrix needs to be
1337 * condensed and compressed. This function is the appropriate choice for
1338 * applying inhomogeneous constraints.
1339 *
1340 * The current object must be closed to call this function.
1341 *
1342 * See the general documentation of this class for more detailed
1343 * information.
1344 */
1345 template <typename VectorType>
1346 void
1347 condense(SparseMatrix<number> &matrix, VectorType &vector) const;
1348
1349 /**
1350 * Same function as above, but condenses square block sparse matrices and
1351 * vectors.
1352 */
1353 template <typename BlockVectorType>
1354 void
1355 condense(BlockSparseMatrix<number> &matrix, BlockVectorType &vector) const;
1356
1357 /**
1358 * Set the values of all constrained DoFs in a vector to zero. The @p
1359 * VectorType may be a Vector<float>, Vector<number>,
1360 * BlockVector<tt><...></tt>, a PETSc or Trilinos vector wrapper class, or
1361 * any other type having the same interface.
1362 */
1363 template <typename VectorType>
1364 void
1365 set_zero(VectorType &vec) const;
1366
1367 /**
1368 * @}
1369 */
1370
1371 /**
1372 * @name Eliminating constraints from linear systems during their creation
1373 * @{
1374 */
1375
1376 /**
1377 * This function takes a vector of local contributions (@p local_vector)
1378 * corresponding to the degrees of freedom indices given in @p
1379 * local_dof_indices and distributes them to the global vector. In other
1380 * words, this function implements a
1381 * [scatter
1382 * operation](https://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing)).
1383 * In most
1384 * cases, these local contributions will be the result of an integration
1385 * over a cell or face of a cell. However, as long as @p local_vector and @p
1386 * local_dof_indices have the same number of elements, this function is
1387 * happy with whatever it is given.
1388 *
1389 * In contrast to the similar function in the DoFAccessor class, this
1390 * function also takes care of constraints, i.e. if one of the elements of
1391 * @p local_dof_indices belongs to a constrained node, then rather than
1392 * writing the corresponding element of @p local_vector into @p
1393 * global_vector, the element is distributed to the entries in the global
1394 * vector to which this particular degree of freedom is constrained.
1395 *
1396 * Thus, by using this function to distribute local contributions to the
1397 * global object, one saves the call to the condense function after the
1398 * vectors and matrices are fully assembled. On the other hand, by
1399 * consequence, the function does not only write into the entries enumerated
1400 * by the @p local_dof_indices array, but also (possibly) others as
1401 * necessary.
1402 *
1403 * Note that this function will apply all constraints as if they were
1404 * homogeneous. For correctly setting inhomogeneous constraints, use the
1405 * similar function with a matrix argument or the function with both matrix
1406 * and vector arguments.
1407 *
1408 * @note This function in itself is thread-safe, i.e., it works properly
1409 * also when several threads call it simultaneously. However, the function
1410 * call is only thread-safe if the underlying global vector allows for
1411 * simultaneous access and the access is not to rows with the same global
1412 * index at the same time. This needs to be made sure from the caller's
1413 * site. There is no locking mechanism inside this method to prevent data
1414 * races.
1415 *
1416 * @param[in] local_vector Vector of local contributions.
1417 * @param[in] local_dof_indices Local degrees of freedom indices
1418 * corresponding to the vector of local contributions.
1419 * @param[out] global_vector The global vector to which all local
1420 * contributions will be added.
1421 */
1422 template <class InVector, class OutVector>
1423 void
1424 distribute_local_to_global(const InVector &local_vector,
1425 const std::vector<size_type> &local_dof_indices,
1426 OutVector &global_vector) const;
1427
1428 /**
1429 * This function takes a vector of local contributions (@p local_vector)
1430 * corresponding to the degrees of freedom indices given in @p
1431 * local_dof_indices and distributes them to the global vector. In other
1432 * words, this function implements a
1433 * [scatter
1434 * operation](https://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing)).
1435 * In most
1436 * cases, these local contributions will be the result of an integration
1437 * over a cell or face of a cell. However, as long as @p local_vector and @p
1438 * local_dof_indices have the same number of elements, this function is
1439 * happy with whatever it is given.
1440 *
1441 * In contrast to the similar function in the DoFAccessor class, this
1442 * function also takes care of constraints, i.e. if one of the elements of
1443 * @p local_dof_indices belongs to a constrained node, then rather than
1444 * writing the corresponding element of @p local_vector into @p
1445 * global_vector, the element is distributed to the entries in the global
1446 * vector to which this particular degree of freedom is constrained.
1447 *
1448 * Thus, by using this function to distribute local contributions to the
1449 * global object, one saves the call to the condense function after the
1450 * vectors and matrices are fully assembled. On the other hand, by
1451 * consequence, the function does not only write into the entries enumerated
1452 * by the @p local_dof_indices array, but also (possibly) others as
1453 * necessary. This includes writing into diagonal elements of the matrix if
1454 * the corresponding degree of freedom is constrained.
1455 *
1456 * The fourth argument <tt>local_matrix</tt> is intended to be used in case
1457 * one wants to apply inhomogeneous constraints on the vector only. Such a
1458 * situation could be where one wants to assemble of a right hand side
1459 * vector on a problem with inhomogeneous constraints, but the global matrix
1460 * has been assembled previously. A typical example of this is a time
1461 * stepping algorithm where the @ref GlossStiffnessMatrix "stiffness matrix" is assembled once, and the
1462 * right hand side updated every time step. Note that, however, the entries
1463 * in the columns of the local matrix have to be exactly the same as those
1464 * that have been written into the global matrix. Otherwise, this function
1465 * will not be able to correctly handle inhomogeneities.
1466 *
1467 * @note This function in itself is thread-safe, i.e., it works properly
1468 * also when several threads call it simultaneously. However, the function
1469 * call is only thread-safe if the underlying global vector allows for
1470 * simultaneous access and the access is not to rows with the same global
1471 * index at the same time. This needs to be made sure from the caller's
1472 * site. There is no locking mechanism inside this method to prevent data
1473 * races.
1474 */
1475 template <typename VectorType>
1476 void
1477 distribute_local_to_global(const Vector<number> &local_vector,
1478 const std::vector<size_type> &local_dof_indices,
1479 VectorType &global_vector,
1480 const FullMatrix<number> &local_matrix) const;
1481
1482 /**
1483 * Same as the previous function, except that it uses two (possibly) different
1484 * index sets to correctly handle inhomogeneities when the local matrix is
1485 * computed from a combination of two neighboring elements, for example for an
1486 * edge integral term in DG. Note that in the case that these two elements
1487 * have different polynomial degree, the local matrix is rectangular.
1488 *
1489 * <tt>local_dof_indices_row</tt> is the set of row indices and
1490 * <tt>local_dof_indices_col</tt> is the set of column indices of the local
1491 * matrix. <tt>diagonal=false</tt> says whether the two index sets are equal
1492 * or not.
1493 *
1494 * If both index sets are equal, <tt>diagonal</tt> must be set to true or we
1495 * simply use the previous function. If both index sets are different
1496 * (diagonal=false) the <tt>global_vector</tt> is modified to handle
1497 * inhomogeneities but no entries from <tt>local_vector</tt> are added. Note
1498 * that the edge integrals for inner edged for DG do not contribute any values
1499 * to the right hand side.
1500 */
1501 template <typename VectorType>
1502 void
1503 distribute_local_to_global(
1504 const Vector<number> &local_vector,
1505 const std::vector<size_type> &local_dof_indices_row,
1506 const std::vector<size_type> &local_dof_indices_col,
1507 VectorType &global_vector,
1508 const FullMatrix<number> &local_matrix,
1509 bool diagonal = false) const;
1510
1511 /**
1512 * Enter a single value into a result vector, obeying constraints.
1513 */
1514 template <typename VectorType>
1515 void
1516 distribute_local_to_global(const size_type index,
1517 const number value,
1518 VectorType &global_vector) const;
1519
1520 /**
1521 * This function takes a pointer to a vector of local contributions (@p
1522 * local_vector) corresponding to the degrees of freedom indices given in @p
1523 * local_dof_indices and distributes them to the global vector. In other
1524 * words, this function implements a
1525 * [scatter
1526 * operation](https://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing)).
1527 * In most
1528 * cases, these local contributions will be the result of an integration
1529 * over a cell or face of a cell. However, as long as the entries in @p
1530 * local_dof_indices indicate reasonable global vector entries, this
1531 * function is happy with whatever it is given.
1532 *
1533 * If one of the elements of @p local_dof_indices belongs to a constrained
1534 * node, then rather than writing the corresponding element of @p
1535 * local_vector into @p global_vector, the element is distributed to the
1536 * entries in the global vector to which this particular degree of freedom
1537 * is constrained.
1538 *
1539 * Thus, by using this function to distribute local contributions to the
1540 * global object, one saves the call to the condense function after the
1541 * vectors and matrices are fully assembled. Note that this function
1542 * completely ignores inhomogeneous constraints.
1543 *
1544 * @note This function in itself is thread-safe, i.e., it works properly
1545 * also when several threads call it simultaneously. However, the function
1546 * call is only thread-safe if the underlying global vector allows for
1547 * simultaneous access and the access is not to rows with the same global
1548 * index at the same time. This needs to be made sure from the caller's
1549 * site. There is no locking mechanism inside this method to prevent data
1550 * races.
1551 */
1552 template <typename ForwardIteratorVec,
1553 typename ForwardIteratorInd,
1554 typename VectorType>
1555 void
1556 distribute_local_to_global(ForwardIteratorVec local_vector_begin,
1557 ForwardIteratorVec local_vector_end,
1558 ForwardIteratorInd local_indices_begin,
1559 VectorType &global_vector) const;
1560
1561 /**
1562 * This function takes a matrix of local contributions (@p local_matrix)
1563 * corresponding to the degrees of freedom indices given in @p
1564 * local_dof_indices and distributes them to the global matrix. In other
1565 * words, this function implements a
1566 * [scatter
1567 * operation](https://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing)).
1568 * In most
1569 * cases, these local contributions will be the result of an integration
1570 * over a cell or face of a cell. However, as long as @p local_matrix and @p
1571 * local_dof_indices have the same number of elements, this function is
1572 * happy with whatever it is given.
1573 *
1574 * In contrast to the similar function in the DoFAccessor class, this
1575 * function also takes care of constraints, i.e. if one of the elements of
1576 * @p local_dof_indices belongs to a constrained node, then rather than
1577 * writing the corresponding element of @p local_matrix into @p
1578 * global_matrix, the element is distributed to the entries in the global
1579 * matrix to which this particular degree of freedom is constrained.
1580 *
1581 * With this scheme, we never write into rows or columns of constrained
1582 * degrees of freedom. In order to make sure that the resulting matrix can
1583 * still be inverted, we need to do something with the diagonal elements
1584 * corresponding to constrained nodes. Thus, if a degree of freedom in @p
1585 * local_dof_indices is constrained, we distribute the corresponding entries
1586 * in the matrix, but also add the absolute value of the diagonal entry of
1587 * the local matrix to the corresponding entry in the global matrix.
1588 * Assuming the discretized operator is positive definite, this guarantees
1589 * that the diagonal entry is always non-zero, positive, and of the same
1590 * order of magnitude as the other entries of the matrix. On the other hand,
1591 * when solving a source problem $Au=f$ the exact value of the diagonal
1592 * element is not important, since the value of the respective degree of
1593 * freedom will be overwritten by the distribute() call later on anyway.
1594 *
1595 * @note The procedure described above adds an unforeseeable number of
1596 * artificial eigenvalues to the spectrum of the matrix. Therefore, it is
1597 * recommended to use the equivalent function with two local index vectors
1598 * in such a case.
1599 *
1600 * By using this function to distribute local contributions to the global
1601 * object, one saves the call to the condense function after the vectors and
1602 * matrices are fully assembled.
1603 *
1604 * @note This function in itself is thread-safe, i.e., it works properly
1605 * also when several threads call it simultaneously. However, the function
1606 * call is only thread-safe if the underlying global matrix allows for
1607 * simultaneous access and the access is not to rows with the same global
1608 * index at the same time. This needs to be made sure from the caller's
1609 * site. There is no locking mechanism inside this method to prevent data
1610 * races.
1611 */
1612 template <typename MatrixType>
1613 void
1614 distribute_local_to_global(const FullMatrix<number> &local_matrix,
1615 const std::vector<size_type> &local_dof_indices,
1616 MatrixType &global_matrix) const;
1617
1618 /**
1619 * This function does almost the same as the function above but can treat
1620 * general rectangular matrices. The main difference to achieve this is that
1621 * the diagonal entries in constrained rows are left untouched instead of
1622 * being filled with arbitrary values.
1623 *
1624 * Since the diagonal entries corresponding to eliminated degrees of freedom
1625 * are not set, the result may have a zero eigenvalue, if applied to a
1626 * square matrix. This has to be considered when solving the resulting
1627 * problems. For solving a source problem $Au=f$, it is possible to set the
1628 * diagonal entry after building the matrix by a piece of code of the form
1629 *
1630 * @code
1631 * for (unsigned int i=0;i<matrix.m();++i)
1632 * if (constraints.is_constrained(i))
1633 * matrix.diag_element(i) = 1.;
1634 * @endcode
1635 *
1636 * The value of one which is used here is arbitrary, but in the context of
1637 * Krylov space methods uncritical, since it corresponds to an invariant
1638 * subspace. If the other matrix entries are smaller or larger by a factor
1639 * close to machine accuracy, it may be advisable to adjust it.
1640 *
1641 * For solving eigenvalue problems, this will only add one spurious zero
1642 * eigenvalue (with a multiplicity that is possibly greater than one).
1643 * Taking this into account, nothing else has to be changed.
1644 */
1645 template <typename MatrixType>
1646 void
1647 distribute_local_to_global(const FullMatrix<number> &local_matrix,
1648 const std::vector<size_type> &row_indices,
1649 const std::vector<size_type> &col_indices,
1650 MatrixType &global_matrix) const;
1651
1652 /**
1653 * This function does almost the same as the function above for general
1654 * rectangular matrices but uses different AffineConstraints objects on the
1655 * row and column indices. The convention is that row indices are constrained
1656 * according to the calling AffineConstraints <code>*this</code>, whereas
1657 * column indices are constrained according to the given AffineConstraints
1658 * <code>column_affine_constraints</code>. This function allows to handle the
1659 * case where rows and columns of a matrix are represented by different
1660 * function spaces with their own enumeration of indices, as e.g. in mixed
1661 * finite element problems with separate DoFHandler objects or for flux
1662 * matrices between different levels in multigrid methods.
1663 *
1664 * Like the other method with separate slots for row and column indices,
1665 * this method does not add diagonal entries to eliminated degrees of
1666 * freedom. See there for a more elaborate description.
1667 */
1668 template <typename MatrixType>
1669 void
1670 distribute_local_to_global(const FullMatrix<number> &local_matrix,
1671 const std::vector<size_type> &row_indices,
1672 const AffineConstraints &column_affine_constraints,
1673 const std::vector<size_type> &column_indices,
1674 MatrixType &global_matrix) const;
1675
1676 /**
1677 * This function simultaneously writes elements into matrix and vector,
1678 * according to the constraints specified by the calling AffineConstraints.
1679 * In other words, it performs the
1680 * [scatter
1681 * operation](https://en.wikipedia.org/wiki/Gather-scatter_(vector_addressing))
1682 * of the corresponding functions for matrices and vectors at the same time.
1683 * This function can correctly handle inhomogeneous constraints as well. For
1684 * the parameter use_inhomogeneities_for_rhs see the documentation in
1685 * @ref constraints
1686 * topic.
1687 *
1688 * @note This function in itself is thread-safe, i.e., it works properly
1689 * also when several threads call it simultaneously. However, the function
1690 * call is only thread-safe if the underlying global matrix and vector allow
1691 * for simultaneous access and the access is not to rows with the same
1692 * global index at the same time. This needs to be made sure from the
1693 * caller's site. There is no locking mechanism inside this method to
1694 * prevent data races.
1695 */
1696 template <typename MatrixType, typename VectorType>
1697 void
1698 distribute_local_to_global(const FullMatrix<number> &local_matrix,
1699 const Vector<number> &local_vector,
1700 const std::vector<size_type> &local_dof_indices,
1701 MatrixType &global_matrix,
1702 VectorType &global_vector,
1703 bool use_inhomogeneities_for_rhs = false) const;
1704
1705 /**
1706 * Do a similar operation as the distribute_local_to_global() function that
1707 * distributes writing entries into a matrix for constrained degrees of
1708 * freedom, except that here we don't write into a matrix but only allocate
1709 * sparsity pattern entries.
1710 *
1711 * As explained in the
1712 * @ref hp_paper "hp-paper"
1713 * and in step-27, first allocating a sparsity pattern and later coming back
1714 * and allocating additional entries for those matrix entries that will be
1715 * written to due to the elimination of constrained degrees of freedom
1716 * (using AffineConstraints::condense() ), can be a very expensive procedure.
1717 * It is cheaper to allocate these entries right away without having to do a
1718 * second pass over the sparsity pattern object. This function does exactly
1719 * that.
1720 *
1721 * Because the function only allocates entries in a sparsity pattern, all it
1722 * needs to know are the degrees of freedom that couple to each other.
1723 * Unlike the previous function, no actual values are written, so the second
1724 * input argument is not necessary here.
1725 *
1726 * The third argument to this function, keep_constrained_entries determines
1727 * whether the function shall allocate entries in the sparsity pattern at
1728 * all for entries that will later be set to zero upon condensation of the
1729 * matrix. These entries are necessary if the matrix is built unconstrained,
1730 * and only later condensed. They are not necessary if the matrix is built
1731 * using the distribute_local_to_global() function of this class which
1732 * distributes entries right away when copying a local matrix into a global
1733 * object. The default of this argument is true, meaning to allocate the few
1734 * entries that may later be set to zero.
1735 *
1736 * By default, the function adds entries for all pairs of indices given in
1737 * the first argument to the sparsity pattern (unless
1738 * keep_constrained_entries is false). However, sometimes one would like to
1739 * only add a subset of all of these pairs. In that case, the last argument
1740 * can be used which specifies a boolean mask which of the pairs of indices
1741 * should be considered. If the mask is false for a pair of indices, then no
1742 * entry will be added to the sparsity pattern for this pair, irrespective
1743 * of whether one or both of the indices correspond to constrained degrees
1744 * of freedom.
1745 *
1746 * This function is not typically called from user code, but is used in the
1747 * DoFTools::make_sparsity_pattern() function when passed an
1748 * AffineConstraints object.
1749 *
1750 * @note This function in itself is thread-safe, i.e., it works properly
1751 * also when several threads call it simultaneously. However, the function
1752 * call is only thread-safe if the underlying global sparsity pattern allows
1753 * for simultaneous access and the access is not to rows with the same
1754 * global index at the same time. This needs to be made sure from the
1755 * caller's site. There is no locking mechanism inside this method to
1756 * prevent data races.
1757 */
1758 void
1759 add_entries_local_to_global(
1760 const std::vector<size_type> &local_dof_indices,
1761 SparsityPatternBase &sparsity_pattern,
1762 const bool keep_constrained_entries = true,
1763 const Table<2, bool> &dof_mask = Table<2, bool>()) const;
1764
1765 /**
1766 * Similar to the other function, but for non-quadratic sparsity patterns.
1767 */
1768 void
1769 add_entries_local_to_global(
1770 const std::vector<size_type> &row_indices,
1771 const std::vector<size_type> &col_indices,
1772 SparsityPatternBase &sparsity_pattern,
1773 const bool keep_constrained_entries = true,
1774 const Table<2, bool> &dof_mask = Table<2, bool>()) const;
1775
1776 /**
1777 * Similar to the other function, but for non-quadratic sparsity patterns, and
1778 * for different constraints in the column space.
1779 */
1780 void
1781 add_entries_local_to_global(
1782 const std::vector<size_type> &row_indices,
1783 const AffineConstraints<number> &col_constraints,
1784 const std::vector<size_type> &col_indices,
1785 SparsityPatternBase &sparsity_pattern,
1786 const bool keep_constrained_entries = true,
1787 const Table<2, bool> &dof_mask = Table<2, bool>()) const;
1788
1789 /**
1790 * This function imports values from a global vector (@p global_vector) by
1791 * applying the constraints to a vector of local values, expressed in
1792 * iterator format. In most cases, the local values will be identified by
1793 * the local dof values on a cell. However, as long as the entries in @p
1794 * local_dof_indices indicate reasonable global vector entries, this
1795 * function is happy with whatever it is given.
1796 *
1797 * If one of the elements of @p local_dof_indices belongs to a constrained
1798 * node, then rather than writing the corresponding element of @p
1799 * global_vector into @p local_vector, the constraints are resolved as the
1800 * respective distribute function does, i.e., the local entry is constructed
1801 * from the global entries to which this particular degree of freedom is
1802 * constrained.
1803 *
1804 * In contrast to the similar function get_dof_values in the DoFAccessor
1805 * class, this function does not need the constrained values to be correctly
1806 * set (i.e., distribute to be called).
1807 */
1808 template <typename ForwardIteratorVec,
1809 typename ForwardIteratorInd,
1810 typename VectorType>
1811 void
1812 get_dof_values(const VectorType &global_vector,
1813 ForwardIteratorInd local_indices_begin,
1814 ForwardIteratorVec local_vector_begin,
1815 ForwardIteratorVec local_vector_end) const;
1816
1817 /**
1818 * @}
1819 */
1820
1821 /**
1822 * @name Dealing with constraints after solving a linear system
1823 * @{
1824 */
1825
1826 /**
1827 * Given a vector, set all constrained degrees of freedom to values so
1828 * that the constraints are satisfied. For example, if the current object
1829 * stores the constraint $x_3=\frac 12 x_1 + \frac 12 x_2$, then this
1830 * function will read the values of $x_1$ and $x_2$ from the given vector
1831 * and set the element $x_3$ according to this constraints. Similarly, if
1832 * the current object stores the constraint $x_{42}=208$, then this
1833 * function will set the 42nd element of the given vector to 208.
1834 *
1835 * @note If this function is called with a parallel vector @p vec, then the
1836 * vector must not contain ghost elements.
1837 */
1838 template <typename VectorType>
1839 void
1840 distribute(VectorType &vec) const;
1841
1842 /**
1843 * @}
1844 */
1845
1846 /**
1847 * This class represents one constraint in an AffineConstraints object.
1848 */
1849 struct ConstraintLine
1850 {
1851 /**
1852 * A data type in which we store the list of entries that make up the
1853 * homogeneous part of a constraint.
1854 */
1855 using Entries = std::vector<std::pair<size_type, number>>;
1856
1857 /**
1858 * Global DoF index of this line. Since only very few lines are stored,
1859 * we can not assume a specific order and have to store the index
1860 * explicitly.
1861 */
1862 size_type index;
1863
1864 /**
1865 * Row numbers and values of the entries in this line.
1866 *
1867 * For the reason why we use a vector instead of a map and the
1868 * consequences thereof, the same applies as what is said for
1869 * AffineConstraints::lines.
1870 */
1871 Entries entries;
1872
1873 /**
1874 * Value of the inhomogeneity.
1875 */
1876 number inhomogeneity;
1877
1878 /**
1879 * Default constructor.
1880 */
1881 ConstraintLine(const size_type &index = numbers::invalid_dof_index,
1882 const typename AffineConstraints<
1883 number>::ConstraintLine::Entries &entries = {},
1884 const number inhomogeneity = 0.0);
1885
1886 /**
1887 * Copy constructor.
1888 */
1889 ConstraintLine(const ConstraintLine &other) = default;
1890
1891 /**
1892 * Move constructor.
1893 */
1894 ConstraintLine(ConstraintLine &&other) noexcept = default;
1895
1896 /**
1897 * Copy assignment.
1898 */
1899 ConstraintLine &
1900 operator=(const ConstraintLine &other) = default;
1901
1902 /**
1903 * Move assignment.
1904 */
1905 ConstraintLine &
1906 operator=(ConstraintLine &&other) noexcept = default;
1907
1908 /**
1909 * Determine an estimate for the memory consumption (in bytes) of this
1910 * object.
1911 */
1912 std::size_t
1913 memory_consumption() const;
1914
1915 /**
1916 * Write and read the data of this object from a stream for the purpose
1917 * of serialization using the [BOOST serialization
1918 * library](https://www.boost.org/doc/libs/1_74_0/libs/serialization/doc/index.html).
1919 */
1920 template <class Archive>
1921 void
1922 serialize(Archive &ar, const unsigned int)
1923 {
1924 ar &index &entries &inhomogeneity;
1925 }
1926
1927 /**
1928 * Swap function.
1929 */
1930 friend void
1931 swap(ConstraintLine &l1, ConstraintLine &l2) noexcept
1932 {
1933 std::swap(l1.index, l2.index);
1934 std::swap(l1.entries, l2.entries);
1935 std::swap(l1.inhomogeneity, l2.inhomogeneity);
1936 }
1937 };
1938
1939 /**
1940 * Alias for the iterator type that is used in the LineRange container.
1941 */
1942 using const_iterator = typename std::vector<ConstraintLine>::const_iterator;
1943
1944 /**
1945 * Alias for the return type used by get_lines().
1946 */
1947 using LineRange = boost::iterator_range<const_iterator>;
1948
1949 /**
1950 * Return a range object containing (const) iterators to all line entries
1951 * stored in the AffineConstraints container. Such a range is useful to
1952 * initialize range-based for loops as supported by C++11.
1953 *
1954 * @return A range object for the half open range <code>[this->begin(),
1955 * this->end())</code> of line entries.
1956 */
1957 LineRange
1958 get_lines() const;
1959
1960 /**
1961 * Check if the current object is consistent on all processors
1962 * in a distributed computation.
1963 *
1964 * This method checks if all processors agree on the constraints for their
1965 * local lines as given by @p locally_active_dofs. This method is a collective
1966 * operation and will return `true` only if all processors are consistent.
1967 *
1968 * Please supply the owned DoFs per processor as returned by
1969 * `Utilities::MPI::all_gather(MPI_Comm, DoFHandler::locally_owned_dofs())` as
1970 * @p locally_owned_dofs and the result of
1971 * DoFTools::extract_locally_active_dofs() as
1972 * @p locally_active_dofs. The former is used to determine ownership of the
1973 * specific DoF, while the latter is used as the set of rows that need to be
1974 * checked.
1975 *
1976 * If @p verbose is set to `true`, additional debug information is written
1977 * to `std::cout`.
1978 *
1979 * @note This method exchanges all constraint information of locally active
1980 * lines and is as such slow for large computations and should probably
1981 * only be used in debug mode. We do not check all lines returned by
1982 * get_local_lines() but only the locally active ones, as we allow processors
1983 * to not know about some locally relevant rows.
1984 *
1985 * @return Whether all AffineConstraints objects are consistent. Returns
1986 * the same value on all processors.
1987 */
1988 bool
1989 is_consistent_in_parallel(const std::vector<IndexSet> &locally_owned_dofs,
1990 const IndexSet &locally_active_dofs,
1991 const MPI_Comm mpi_communicator,
1992 const bool verbose = false) const;
1993
1994 /**
1995 * Make the constraints that are locally stored on the current object
1996 * consistent on all MPI processes in a distributed computation.
1997 *
1998 * The IndexSet @p locally_owned_dofs conforms to all DoFs that are locally
1999 * owned on the current process, that is typically what you get from
2000 * DoFHandler::locally_owned_dofs().
2001 *
2002 * The IndexSet @p constraints_to_make_consistent shall contain all DoF
2003 * indices for which we want to store the complete constraints for. Which DoFs
2004 * these might be depends on your actual use case; in general, these are
2005 * the degrees of freedoms for which you compute contributions to the matrix
2006 * and right hand side of a linear system. For most applications in
2007 * which you are using continuous Galerkin methods, you would want to use
2008 * locally active DoFs here, obtained via
2009 * DoFTools::extract_locally_active_dofs(). This is because you compute
2010 * contributions for the linear system only on the locally owned cells,
2011 * and the degrees of freedom located there -- i.e., exactly the locally
2012 * active degrees of freedom (see
2013 * @ref GlossLocallyActiveDof "this glossary entry"). On the other hand,
2014 * for discontinuous Galerkin methods, you might need consistent information
2015 * on all locally relevant DoFs due to the need to compute face integrals
2016 * between locally owned and ghost cells, with contributions computed also
2017 * for matrix and right hand side entries that correspond to degrees of
2018 * freedom on ghost cells, i.e., DoFs that are owned by other processes.
2019 * In that case, you need to know about constraints also for degrees of
2020 * freedom on locally relevant DoFs, and in that case you want to pass
2021 * as second argument to this function what you get from
2022 * DoFTools::extract_locally_relevant_dofs(). It is worth noting that the
2023 * same happens if you use a continuous Galerkin method but if your
2024 * bilinear form contains terms computed on faces -- for example to
2025 * penalize certain terms when solving the biharmonic equation (see,
2026 * for example, step-47).
2027 *
2028 * At the end of this function, the current object only stores constraints
2029 * for degrees of freedom whose indices are listed in the
2030 * second argument, @p constraints_to_make_consistent. In other words, while
2031 * DoFTools::make_hanging_node_constraints() may compute constraints
2032 * also for degrees of freedom at the interface between two ghost cells
2033 * (these DoFs are locally *relevant*), if you pass as second argument only
2034 * the set of locally *active* DoFs, this function will at the end have
2035 * forgotten constraints about all DoFs that are locally relevant but
2036 * not locally active.
2037 *
2038 * This function updates the locally stored constraints (or local_lines) of
2039 * this object, whenever a DoF is constrained against another that we have not
2040 * known of before. After calling this function, it might be necessary to use
2041 * the IndexSet retrieved by get_local_lines() when initializing data
2042 * structures built on top of the AffineConstraints object, for example:
2043 * @code
2044 * DynamicSparsityPattern dsp(constraints.get_local_lines());
2045 * LinearAlgebra::distributed::Vector<double> solution(
2046 * locally_owned_dofs, constraints.get_local_lines(), mpi_communicator);
2047 * @endcode
2048 *
2049 * @note This function internally calls close(). As a consequence, whether
2050 * or not you have called close() before, the current object will be
2051 * closed after this function.
2052 */
2053 void
2054 make_consistent_in_parallel(const IndexSet &locally_owned_dofs,
2055 const IndexSet &constraints_to_make_consistent,
2056 const MPI_Comm mpi_communicator);
2057
2058 /**
2059 * Exception
2060 *
2061 * @ingroup Exceptions
2062 */
2063 DeclExceptionMsg(
2064 ExcMatrixIsClosed,
2065 "You are attempting an operation on an AffineConstraints object "
2066 "that requires the object to not be 'closed', i.e., for which you "
2067 "must not already have called the close() member function. But the "
2068 "object is already closed, and so the operation can not be "
2069 "performed.");
2070 /**
2071 * Exception
2072 *
2073 * @ingroup Exceptions
2074 */
2075 DeclExceptionMsg(
2076 ExcMatrixNotClosed,
2077 "You are attempting an operation on an AffineConstraints object "
2078 "that requires the object to be 'closed', i.e., for which you "
2079 "needed to call the close() member function. But the object "
2080 "is not currently closed, and so the operation can not be "
2081 "performed.");
2082 /**
2083 * Exception
2084 *
2085 * @ingroup Exceptions
2086 */
2087 DeclException1(ExcLineInexistent,
2088 size_type,
2089 << "The specified line " << arg1 << " does not exist.");
2090 /**
2091 * Exception
2092 *
2093 * @ingroup Exceptions
2094 */
2095 DeclException4(ExcEntryAlreadyExists,
2096 size_type,
2097 size_type,
2098 number,
2099 number,
2100 << "The entry for the indices " << arg1 << " and " << arg2
2101 << " already exists, but the values " << arg3 << " (old) and "
2102 << arg4 << " (new) differ "
2103 << "by " << (arg4 - arg3) << '.');
2104 /**
2105 * Exception
2106 *
2107 * @ingroup Exceptions
2108 */
2109 DeclException2(ExcDoFConstrainedToConstrainedDoF,
2110 int,
2111 int,
2112 << "You tried to constrain DoF " << arg1 << " to DoF " << arg2
2113 << ", but that one is also constrained. This is not allowed!");
2114 /**
2115 * Exception.
2116 *
2117 * @ingroup Exceptions
2118 */
2119 DeclException1(ExcDoFIsConstrainedFromBothObjects,
2120 size_type,
2121 << "Degree of freedom " << arg1
2122 << " is constrained from both object in a merge operation.");
2123 /**
2124 * Exception
2125 *
2126 * @ingroup Exceptions
2127 */
2128 DeclException1(ExcDoFIsConstrainedToConstrainedDoF,
2129 size_type,
2130 << "In the given argument a degree of freedom is constrained "
2131 << "to another DoF with number " << arg1
2132 << ", which however is constrained by this object. This is not"
2133 << " allowed.");
2134 /**
2135 * Exception
2136 *
2137 * @ingroup Exceptions
2138 */
2139 DeclException1(ExcRowNotStoredHere,
2140 size_type,
2141 << "The index set given to this constraints object indicates "
2142 << "constraints for degree of freedom " << arg1
2143 << " should not be stored by this object, but a constraint "
2144 << "is being added.");
2145
2146 /**
2147 * Exception
2148 *
2149 * @ingroup Exceptions
2150 */
2151 DeclException2(ExcColumnNotStoredHere,
2152 size_type,
2153 size_type,
2154 << "The index set given to this constraints object indicates "
2155 << "constraints using degree of freedom " << arg2
2156 << " should not be stored by this object, but a constraint "
2157 << "for degree of freedom " << arg1 << " uses it.");
2158
2159 /**
2160 * Exception
2161 *
2162 * @ingroup Exceptions
2163 */
2164 DeclException2(ExcIncorrectConstraint,
2165 int,
2166 int,
2167 << "While distributing the constraint for DoF " << arg1
2168 << ", it turns out that one of the processors "
2169 << "who own the " << arg2 << " degrees of freedom that x_"
2170 << arg1 << " is constrained against does not know about "
2171 << "the constraint on x_" << arg1
2172 << ". Did you not initialize the AffineConstraints container "
2173 << "with the appropriate locally_relevant set so "
2174 << "that every processor who owns a DoF that constrains "
2175 << "another DoF also knows about this constraint?");
2176
2177 template <typename>
2178 friend class AffineConstraints;
2179
2180 private:
2181 /**
2182 * Store the lines of the matrix. Entries are usually appended in an
2183 * arbitrary order and insertion into a vector is done best at the end, so
2184 * the order is unspecified after all entries are inserted. Sorting of the
2185 * entries takes place when calling the <tt>close()</tt> function.
2186 *
2187 * We could, instead of using a vector, use an associative array, like a map
2188 * to store the lines. This, however, would mean a much more fragmented heap
2189 * since it allocates many small objects, and would additionally make usage
2190 * of this matrix much slower.
2191 */
2192 std::vector<ConstraintLine> lines;
2193
2194 /**
2195 * A list of size_type that contains the position of the ConstraintLine of a
2196 * constrained degree of freedom, or numbers::invalid_size_type if the
2197 * degree of freedom is not constrained. The numbers::invalid_size_type
2198 * return value returns thus whether there is a constraint line for a given
2199 * degree of freedom index. Note that this class has no notion of how many
2200 * degrees of freedom there really are, so if we check whether there is a
2201 * constraint line for a given degree of freedom, then this vector may
2202 * actually be shorter than the index of the DoF we check for.
2203 *
2204 * This field exists since when adding a new constraint line we have to
2205 * figure out whether it already exists. Previously, we would simply walk
2206 * the unsorted list of constraint lines until we either hit the end or
2207 * found it. This algorithm is O(N) if N is the number of constraints, which
2208 * makes it O(N^2) when inserting all constraints. For large problems with
2209 * many constraints, this could easily take 5-10 per cent of the total run
2210 * time. With this field, we can save this time since we find any constraint
2211 * in O(1) time or get to know that it a certain degree of freedom is not
2212 * constrained.
2213 *
2214 * To make things worse, traversing the list of existing constraints
2215 * requires reads from many different places in memory. Thus, in large 3d
2216 * applications, the add_line() function showed up very prominently in the
2217 * overall compute time, mainly because it generated a lot of cache misses.
2218 * This should also be fixed by using the O(1) algorithm to access the
2219 * fields of this array.
2220 *
2221 * The field is useful in a number of other contexts as well, e.g. when one
2222 * needs random access to the constraints as in all the functions that apply
2223 * constraints on the fly while add cell contributions into vectors and
2224 * matrices.
2225 */
2226 std::vector<size_type> lines_cache;
2227
2228 /**
2229 * This IndexSet denotes the set of locally owned DoFs (or, more correctly,
2230 * the locally owned vector elements when operating on parallel vectors)
2231 * and is used in the distribute() function when determining for which
2232 * degrees of freedom to import dependent DoFs.
2233 */
2234 IndexSet locally_owned_dofs;
2235
2236 /**
2237 * This IndexSet is used to limit the lines to save in the AffineConstraints
2238 * to a subset. This is necessary, because the lines_cache vector would
2239 * become too big in a distributed calculation.
2240 */
2241 IndexSet local_lines;
2242
2243 /**
2244 * The set of elements that are necessary to call distribute(). Because
2245 * we need to set locally owned constrained elements of a vector, the
2246 * needed elements include all vector entries that these constrained
2247 * elements depend on -- which may be owned by other processes.
2248 *
2249 * This variable is set in close().
2250 */
2251 IndexSet needed_elements_for_distribute;
2252
2253 /**
2254 * Store whether the arrays are sorted. If so, no new entries can be added.
2255 */
2256 bool sorted;
2257
2258 mutable Threads::ThreadLocalStorage<
2259 internal::AffineConstraints::ScratchData<number>>
2260 scratch_data;
2261
2262 /**
2263 * Internal function to calculate the index of line @p line_n in the vector
2264 * lines_cache using local_lines.
2265 */
2266 size_type
2267 calculate_line_index(const size_type line_n) const;
2268
2269 /**
2270 * This function actually implements the local_to_global function for
2271 * standard (non-block) matrices.
2272 */
2273 template <typename MatrixType, typename VectorType>
2274 void
2275 distribute_local_to_global(const FullMatrix<number> &local_matrix,
2276 const Vector<number> &local_vector,
2277 const std::vector<size_type> &local_dof_indices,
2278 MatrixType &global_matrix,
2279 VectorType &global_vector,
2280 const bool use_inhomogeneities_for_rhs,
2281 const std::bool_constant<false>) const;
2282
2283 /**
2284 * This function actually implements the local_to_global function for block
2285 * matrices.
2286 */
2287 template <typename MatrixType, typename VectorType>
2288 void
2289 distribute_local_to_global(const FullMatrix<number> &local_matrix,
2290 const Vector<number> &local_vector,
2291 const std::vector<size_type> &local_dof_indices,
2292 MatrixType &global_matrix,
2293 VectorType &global_vector,
2294 const bool use_inhomogeneities_for_rhs,
2295 const std::bool_constant<true>) const;
2296
2297 /**
2298 * Internal helper function for distribute_local_to_global function.
2299 *
2300 * Creates a list of affected global rows for distribution, including the
2301 * local rows where the entries come from. The list is sorted according to
2302 * the global row indices.
2303 */
2304 void
2305 make_sorted_row_list(const std::vector<size_type> &local_dof_indices,
2306 internal::AffineConstraints::GlobalRowsFromLocal<number>
2307 &global_rows) const;
2308
2309 /**
2310 * Internal helper function for add_entries_local_to_global function.
2311 *
2312 * Creates a list of affected rows for distribution without any additional
2313 * information, otherwise similar to the other make_sorted_row_list()
2314 * function.
2315 */
2316 void
2317 make_sorted_row_list(const std::vector<size_type> &local_dof_indices,
2318 std::vector<size_type> &active_dofs) const;
2319
2320 /**
2321 * Internal helper function for distribute_local_to_global function.
2322 */
2323 template <typename MatrixScalar, typename VectorScalar>
2324 typename ProductType<VectorScalar, MatrixScalar>::type
2325 resolve_vector_entry(
2326 const size_type i,
2327 const internal::AffineConstraints::GlobalRowsFromLocal<number> &global_rows,
2328 const Vector<VectorScalar> &local_vector,
2329 const std::vector<size_type> &local_dof_indices,
2330 const FullMatrix<MatrixScalar> &local_matrix) const;
2331 };
2332
2333 /* ---------------- template and inline functions ----------------- */
2334
2335 template <typename number>
2336 inline AffineConstraints<number>::AffineConstraints()
2337 : AffineConstraints<number>(IndexSet(), IndexSet())
2338 {}
2339
2340
2341
2342 template <typename number>
2343 inline AffineConstraints<number>::AffineConstraints(
2344 const IndexSet &locally_stored_constraints)
2345 : AffineConstraints<number>(locally_stored_constraints,
2346 locally_stored_constraints)
2347 {}
2348
2349
2350
2351 template <typename number>
2352 inline AffineConstraints<number>::AffineConstraints(
2353 const IndexSet &locally_owned_dofs,
2354 const IndexSet &locally_stored_constraints)
2355 : lines()
2356 , locally_owned_dofs(locally_owned_dofs)
2357 , local_lines(locally_stored_constraints)
2358 , sorted(false)
2359 {
2360 Assert(locally_owned_dofs.is_subset_of(locally_stored_constraints),
2361 ExcMessage("The set of locally stored constraints needs to be a "
2362 "superset of the locally owned DoFs."));
2363
2364 // make sure the IndexSet is compressed. Otherwise this can lead to crashes
2365 // that are hard to find (only happen in release mode).
2366 // see tests/mpi/affine_constraints_crash_01
2367 local_lines.compress();
2368 }
2369
2370
2371
2372 template <typename number>
2373 inline AffineConstraints<number>::AffineConstraints(
2374 const AffineConstraints &affine_constraints)
2375 : EnableObserverPointer()
2376 , lines(affine_constraints.lines)
2377 , lines_cache(affine_constraints.lines_cache)
2378 , locally_owned_dofs(affine_constraints.locally_owned_dofs)
2379 , local_lines(affine_constraints.local_lines)
2380 , needed_elements_for_distribute(
2381 affine_constraints.needed_elements_for_distribute)
2382 , sorted(affine_constraints.sorted)
2383 {}
2384
2385
2386
2387 template <typename number>
2388 inline void
2389 AffineConstraints<number>::add_line(const size_type line_n)
2390 {
2391 Assert(sorted == false, ExcMatrixIsClosed());
2392
2393 // the following can happen when we compute with distributed meshes and dof
2394 // handlers and we constrain a degree of freedom whose number we don't have
2395 // locally. if we don't abort here the program will try to allocate several
2396 // terabytes of memory to resize the various arrays below :-)
2397 Assert(line_n != numbers::invalid_size_type, ExcInternalError());
2398 const size_type line_index = calculate_line_index(line_n);
2399
2400 // check whether line already exists; it may, in which case we can just quit
2401 if (is_constrained(line_n))
2402 return;
2403
2404 // if necessary enlarge vector of existing entries for cache
2405 if (line_index >= lines_cache.size())
2406 lines_cache.resize(std::max(2 * static_cast<size_type>(lines_cache.size()),
2407 line_index + 1),
2408 numbers::invalid_size_type);
2409
2410 // push a new line to the end of the list
2411 lines.emplace_back();
2412 lines.back().index = line_n;
2413 lines.back().inhomogeneity = 0.;
2414 lines_cache[line_index] = lines.size() - 1;
2415 }
2416
2417
2418
2419 template <typename number>
2420 inline void
2421 AffineConstraints<number>::add_entry(const size_type constrained_dof_index,
2422 const size_type column,
2423 const number weight)
2424 {
2425 Assert(sorted == false, ExcMatrixIsClosed());
2426 Assert(constrained_dof_index != column,
2427 ExcMessage("Can't constrain a degree of freedom to itself"));
2428
2429 // Ensure that the current line is present in the cache:
2430 const size_type line_index = calculate_line_index(constrained_dof_index);
2431 Assert(line_index < lines_cache.size(),
2432 ExcMessage("The current AffineConstraints does not contain the line "
2433 "for the current entry. Call AffineConstraints::add_line "
2434 "before calling this function."));
2435
2436 // if in debug mode, check whether an entry for this column already exists
2437 // and if it's the same as the one entered at present
2438 //
2439 // in any case: exit the function if an entry for this column already
2440 // exists, since we don't want to enter it twice
2441 Assert(lines_cache[line_index] != numbers::invalid_size_type,
2442 ExcInternalError());
2443 Assert(!local_lines.size() || local_lines.is_element(column),
2444 ExcColumnNotStoredHere(constrained_dof_index, column));
2445 ConstraintLine *line_ptr = &lines[lines_cache[line_index]];
2446 Assert(line_ptr->index == constrained_dof_index, ExcInternalError());
2447 for (const auto &p : line_ptr->entries)
2448 if (p.first == column)
2449 {
2450 Assert(std::abs(p.second - weight) < 1.e-14,
2451 ExcEntryAlreadyExists(
2452 constrained_dof_index, column, p.second, weight));
2453 return;
2454 }
2455
2456 line_ptr->entries.emplace_back(column, weight);
2457 }
2458
2459
2460
2461 template <typename number>
2462 inline void
2463 AffineConstraints<number>::set_inhomogeneity(
2464 const size_type constrained_dof_index,
2465 const number value)
2466 {
2467 const size_type line_index = calculate_line_index(constrained_dof_index);
2468 Assert(line_index < lines_cache.size() &&
2469 lines_cache[line_index] != numbers::invalid_size_type,
2470 ExcMessage("call add_line() before calling set_inhomogeneity()"));
2471 Assert(lines_cache[line_index] < lines.size(), ExcInternalError());
2472 ConstraintLine *line_ptr = &lines[lines_cache[line_index]];
2473 line_ptr->inhomogeneity = value;
2474 }
2475
2476
2477
2478 template <typename number>
2479 template <typename VectorType>
2480 inline void
2481 AffineConstraints<number>::set_zero(VectorType &vec) const
2482 {
2483 // since lines is a private member, we cannot pass it to the functions
2484 // above. therefore, copy the content which is cheap
2485 std::vector<size_type> constrained_lines(lines.size());
2486 for (unsigned int i = 0; i < lines.size(); ++i)
2487 constrained_lines[i] = lines[i].index;
2488 internal::AffineConstraintsImplementation::set_zero_all(constrained_lines,
2489 vec);
2490 }
2491
2492 template <typename number>
2493 inline types::global_dof_index
2494 AffineConstraints<number>::n_constraints() const
2495 {
2496 return lines.size();
2497 }
2498
2499 template <typename number>
2500 inline types::global_dof_index
2501 AffineConstraints<number>::n_identities() const
2502 {
2503 return std::count_if(lines.begin(),
2504 lines.end(),
2505 [](const ConstraintLine &line) {
2506 return (line.entries.size() == 1) &&
2507 (line.entries[0].second == number(1.));
2508 });
2509 }
2510
2511 template <typename number>
2512 inline types::global_dof_index
2513 AffineConstraints<number>::n_inhomogeneities() const
2514 {
2515 return std::count_if(lines.begin(),
2516 lines.end(),
2517 [](const ConstraintLine &line) {
2518 return (line.inhomogeneity != number(0.));
2519 });
2520 }
2521
2522 template <typename number>
2523 inline bool
2524 AffineConstraints<number>::is_constrained(const size_type index) const
2525 {
2526 if (lines.empty())
2527 return false;
2528
2529 const size_type line_index = calculate_line_index(index);
2530 return ((line_index < lines_cache.size()) &&
2531 (lines_cache[line_index] != numbers::invalid_size_type));
2532 }
2533
2534 template <typename number>
2535 inline bool
2536 AffineConstraints<number>::is_inhomogeneously_constrained(
2537 const size_type line_n) const
2538 {
2539 // check whether the entry is constrained. could use is_constrained, but
2540 // that means computing the line index twice
2541 const size_type line_index = calculate_line_index(line_n);
2542 if (line_index >= lines_cache.size() ||
2543 lines_cache[line_index] == numbers::invalid_size_type)
2544 return false;
2545 else
2546 {
2547 Assert(lines_cache[line_index] < lines.size(), ExcInternalError());
2548 return (lines[lines_cache[line_index]].inhomogeneity != number(0.));
2549 }
2550 }
2551
2552 template <typename number>
2553 inline const std::vector<std::pair<types::global_dof_index, number>> *
2554 AffineConstraints<number>::get_constraint_entries(const size_type line_n) const
2555 {
2556 if (lines.empty())
2557 return nullptr;
2558
2559 // check whether the entry is constrained. could use is_constrained, but
2560 // that means computing the line index twice
2561 const size_type line_index = calculate_line_index(line_n);
2562 if (line_index >= lines_cache.size() ||
2563 lines_cache[line_index] == numbers::invalid_size_type)
2564 return nullptr;
2565 else
2566 return &lines[lines_cache[line_index]].entries;
2567 }
2568
2569 template <typename number>
2570 inline number
2571 AffineConstraints<number>::get_inhomogeneity(const size_type line_n) const
2572 {
2573 // check whether the entry is constrained. could use is_constrained, but
2574 // that means computing the line index twice
2575 const size_type line_index = calculate_line_index(line_n);
2576 if (line_index >= lines_cache.size() ||
2577 lines_cache[line_index] == numbers::invalid_size_type)
2578 return 0;
2579 else
2580 return lines[lines_cache[line_index]].inhomogeneity;
2581 }
2582
2583 template <typename number>
2584 inline types::global_dof_index
2585 AffineConstraints<number>::calculate_line_index(const size_type line_n) const
2586 {
2587 // IndexSet is unused (serial case)
2588 if (local_lines.size() == 0)
2589 return line_n;
2590
2591 Assert(local_lines.is_element(line_n), ExcRowNotStoredHere(line_n));
2592
2593 return local_lines.index_within_set(line_n);
2594 }
2595
2596
2597
2598 template <typename number>
2599 inline bool
2600 AffineConstraints<number>::can_store_line(size_type line_n) const
2601 {
2602 return local_lines.size() == 0 || local_lines.is_element(line_n);
2603 }
2604
2605
2606
2607 template <typename number>
2608 inline const IndexSet &
2609 AffineConstraints<number>::get_locally_owned_indices() const
2610 {
2611 return locally_owned_dofs;
2612 }
2613
2614
2615
2616 template <typename number>
2617 inline const IndexSet &
2618 AffineConstraints<number>::get_local_lines() const
2619 {
2620 return local_lines;
2621 }
2622
2623
2624
2625 template <typename number>
2626 template <typename VectorType>
2627 inline void
2628 AffineConstraints<number>::distribute_local_to_global(
2629 const size_type index,
2630 const number value,
2631 VectorType &global_vector) const
2632 {
2633 Assert(lines.empty() || sorted == true, ExcMatrixNotClosed());
2634
2635 if (is_constrained(index) == false)
2636 global_vector(index) += value;
2637 else
2638 {
2639 const ConstraintLine &position =
2640 lines[lines_cache[calculate_line_index(index)]];
2641 for (size_type j = 0; j < position.entries.size(); ++j)
2642 global_vector(position.entries[j].first) +=
2643 value * position.entries[j].second;
2644 }
2645 }
2646
2647 template <typename number>
2648 template <typename ForwardIteratorVec,
2649 typename ForwardIteratorInd,
2650 typename VectorType>
2651 inline void
2652 AffineConstraints<number>::distribute_local_to_global(
2653 ForwardIteratorVec local_vector_begin,
2654 ForwardIteratorVec local_vector_end,
2655 ForwardIteratorInd local_indices_begin,
2656 VectorType &global_vector) const
2657 {
2658 Assert(lines.empty() || sorted == true, ExcMatrixNotClosed());
2659 for (; local_vector_begin != local_vector_end;
2660 ++local_vector_begin, ++local_indices_begin)
2661 {
2662 if (is_constrained(*local_indices_begin) == false)
2663 internal::ElementAccess<VectorType>::add(*local_vector_begin,
2664 *local_indices_begin,
2665 global_vector);
2666 else
2667 {
2668 const ConstraintLine &position =
2669 lines[lines_cache[calculate_line_index(*local_indices_begin)]];
2670 for (size_type j = 0; j < position.entries.size(); ++j)
2671 internal::ElementAccess<VectorType>::add(
2672 (*local_vector_begin) * position.entries[j].second,
2673 position.entries[j].first,
2674 global_vector);
2675 }
2676 }
2677 }
2678
2679 template <typename number>
2680 template <class InVector, class OutVector>
2681 inline void
2682 AffineConstraints<number>::distribute_local_to_global(
2683 const InVector &local_vector,
2684 const std::vector<size_type> &local_dof_indices,
2685 OutVector &global_vector) const
2686 {
2687 Assert(global_vector.has_ghost_elements() == false, ExcGhostsPresent());
2688 Assert(local_vector.size() == local_dof_indices.size(),
2689 ExcDimensionMismatch(local_vector.size(), local_dof_indices.size()));
2690 distribute_local_to_global(local_vector.begin(),
2691 local_vector.end(),
2692 local_dof_indices.begin(),
2693 global_vector);
2694 }
2695
2696 template <typename number>
2697 template <typename ForwardIteratorVec,
2698 typename ForwardIteratorInd,
2699 typename VectorType>
2700 inline void
2701 AffineConstraints<number>::get_dof_values(
2702 const VectorType &global_vector,
2703 ForwardIteratorInd local_indices_begin,
2704 ForwardIteratorVec local_vector_begin,
2705 ForwardIteratorVec local_vector_end) const
2706 {
2707 Assert(lines.empty() || sorted == true, ExcMatrixNotClosed());
2708 for (; local_vector_begin != local_vector_end;
2709 ++local_vector_begin, ++local_indices_begin)
2710 {
2711 if (is_constrained(*local_indices_begin) == false)
2712 *local_vector_begin = global_vector(*local_indices_begin);
2713 else
2714 {
2715 const ConstraintLine &position =
2716 lines[lines_cache[calculate_line_index(*local_indices_begin)]];
2717 typename VectorType::value_type value = position.inhomogeneity;
2718 for (size_type j = 0; j < position.entries.size(); ++j)
2719 value += (global_vector(position.entries[j].first) *
2720 position.entries[j].second);
2721 *local_vector_begin = value;
2722 }
2723 }
2724 }
2725
2726 // Forward declarations
2727 #ifndef DOXYGEN
2728 template <typename MatrixType>
2729 class BlockMatrixBase;
2730 template <typename SparsityPatternType>
2731 class BlockSparsityPatternBase;
2732 template <typename number>
2733 class BlockSparseMatrixEZ;
2734
2735 namespace internal
2736 {
2737 namespace AffineConstraints
2738 {
2739 /**
2740 * A "traits" class that can be used to determine whether a given type is a
2741 * block matrix type or not. For example,
2742 * @code
2743 * IsBlockMatrix<SparseMatrix<number> >::value
2744 * @endcode
2745 * has the value `false`, whereas
2746 * @code
2747 * IsBlockMatrix<BlockSparseMatrix<number> >::value
2748 * @endcode
2749 * is true. This is sometimes useful in template contexts where we may want
2750 * to do things differently depending on whether a template type denotes a
2751 * regular or a block matrix type.
2752 *
2753 * @see
2754 * @ref GlossBlockLA "Block (linear algebra)"
2755 */
2756 template <typename MatrixType>
2757 struct IsBlockMatrix
2758 {
2759 private:
2760 /**
2761 * Overload returning true if the class is derived from BlockMatrixBase,
2762 * which is what block matrices do (with the exception of
2763 * BlockSparseMatrixEZ).
2764 */
2765 template <typename T>
2766 static std::true_type
2767 check(const BlockMatrixBase<T> *);
2768
2769 /**
2770 * Overload for BlockSparseMatrixEZ, which is the only block matrix not
2771 * derived from BlockMatrixBase at the time of writing this class.
2772 */
2773 template <typename T>
2774 static std::true_type
2775 check(const BlockSparseMatrixEZ<T> *);
2776
2777 /**
2778 * Catch all for all other potential types that are then apparently not
2779 * block matrices.
2780 */
2781 static std::false_type
2782 check(...);
2783
2784 public:
2785 /**
2786 * A statically computable value that indicates whether the template
2787 * argument to this class is a block matrix (in fact whether the type is
2788 * derived from BlockMatrixBase<T> or is one of the other block matrix
2789 * types).
2790 */
2791 static const bool value =
2792 std::is_same_v<decltype(check(std::declval<MatrixType *>())),
2793 std::true_type>;
2794 };
2795
2796 // instantiation of the static member
2797 template <typename MatrixType>
2798 const bool IsBlockMatrix<MatrixType>::value;
2799
2800 } // namespace AffineConstraints
2801 } // namespace internal
2802 #endif
2803
2804
2805
2806 template <typename number>
2807 template <typename other_number>
2808 inline void
2809 AffineConstraints<number>::copy_from(
2810 const AffineConstraints<other_number> &other)
2811 {
2812 lines.clear();
2813 lines.reserve(other.lines.size());
2814
2815 for (const auto &l : other.lines)
2816 lines.emplace_back(l.index,
2817 typename ConstraintLine::Entries(l.entries.begin(),
2818 l.entries.end()),
2819 l.inhomogeneity);
2820
2821 lines_cache = other.lines_cache;
2822 local_lines = other.local_lines;
2823 sorted = other.sorted;
2824
2825 locally_owned_dofs = other.locally_owned_dofs;
2826 needed_elements_for_distribute = other.needed_elements_for_distribute;
2827 }
2828
2829
2830 template <typename number>
2831 template <typename other_number>
2832 void
2833 AffineConstraints<number>::merge(
2834 const AffineConstraints<other_number> &other_constraints,
2835 const MergeConflictBehavior merge_conflict_behavior,
2836 const bool allow_different_local_lines)
2837 {
2838 Assert(allow_different_local_lines ||
2839 local_lines == other_constraints.local_lines,
2840 ExcMessage(
2841 "local_lines for this and the other objects are not the same "
2842 "although allow_different_local_lines is false."));
2843
2844 // store the previous state with respect to sorting
2845 const bool object_was_sorted = sorted;
2846 sorted = false;
2847
2848 // first action is to fold into the present object possible constraints
2849 // in the second object. we don't strictly need to do this any more since
2850 // the AffineConstraints container has learned to deal with chains of
2851 // constraints in the close() function, but we have traditionally done
2852 // this and it's not overly hard to do.
2853 //
2854 // for this, loop over all constraints and replace the constraint lines
2855 // with a new one where constraints are replaced if necessary.
2856 typename ConstraintLine::Entries tmp;
2857 for (ConstraintLine &line : lines)
2858 {
2859 tmp.clear();
2860 for (const std::pair<size_type, number> &entry : line.entries)
2861 {
2862 // if the present dof is not stored, or not constrained, or if we
2863 // won't take the constraint from the other object, then simply copy
2864 // it over
2865 if ((other_constraints.local_lines.size() != 0. &&
2866 other_constraints.local_lines.is_element(entry.first) ==
2867 false) ||
2868 other_constraints.is_constrained(entry.first) == false ||
2869 ((merge_conflict_behavior != right_object_wins) &&
2870 other_constraints.is_constrained(entry.first) &&
2871 this->is_constrained(entry.first)))
2872 tmp.push_back(entry);
2873 else
2874 // otherwise resolve further constraints by replacing the old
2875 // entry by a sequence of new entries taken from the other
2876 // object, but with multiplied weights
2877 {
2878 const auto *other_entries =
2879 other_constraints.get_constraint_entries(entry.first);
2880 Assert(other_entries != nullptr, ExcInternalError());
2881
2882 const number weight = entry.second;
2883
2884 for (const auto &other_entry : *other_entries)
2885 tmp.emplace_back(other_entry.first,
2886 other_entry.second * weight);
2887
2888 line.inhomogeneity +=
2889 other_constraints.get_inhomogeneity(entry.first) * weight;
2890 }
2891 }
2892 // finally exchange old and newly resolved line
2893 line.entries.swap(tmp);
2894 }
2895
2896 if (local_lines.size() != 0)
2897 local_lines.add_indices(other_constraints.local_lines);
2898
2899 {
2900 // do not bother to resize the lines cache exactly since it is pretty
2901 // cheap to adjust it along the way.
2902 std::fill(lines_cache.begin(),
2903 lines_cache.end(),
2904 numbers::invalid_size_type);
2905
2906 // reset lines_cache for our own constraints
2907 size_type index = 0;
2908 for (const ConstraintLine &line : lines)
2909 {
2910 const size_type local_line_no = calculate_line_index(line.index);
2911 if (local_line_no >= lines_cache.size())
2912 lines_cache.resize(local_line_no + 1, numbers::invalid_size_type);
2913 lines_cache[local_line_no] = index++;
2914 }
2915
2916 // Add other_constraints to lines cache and our list of constraints
2917 for (const auto &line : other_constraints.lines)
2918 {
2919 const size_type local_line_no = calculate_line_index(line.index);
2920 if (local_line_no >= lines_cache.size())
2921 {
2922 lines_cache.resize(local_line_no + 1, numbers::invalid_size_type);
2923 lines.emplace_back(line.index,
2924 typename ConstraintLine::Entries(
2925 line.entries.begin(), line.entries.end()),
2926 line.inhomogeneity);
2927 lines_cache[local_line_no] = index++;
2928 }
2929 else if (lines_cache[local_line_no] == numbers::invalid_size_type)
2930 {
2931 // there are no constraints for that line yet
2932 lines.emplace_back(line.index,
2933 typename ConstraintLine::Entries(
2934 line.entries.begin(), line.entries.end()),
2935 line.inhomogeneity);
2936 AssertIndexRange(local_line_no, lines_cache.size());
2937 lines_cache[local_line_no] = index++;
2938 }
2939 else
2940 {
2941 // we already store that line
2942 switch (merge_conflict_behavior)
2943 {
2944 case no_conflicts_allowed:
2945 AssertThrow(false,
2946 ExcDoFIsConstrainedFromBothObjects(line.index));
2947 break;
2948
2949 case left_object_wins:
2950 // ignore this constraint
2951 break;
2952
2953 case right_object_wins:
2954 AssertIndexRange(local_line_no, lines_cache.size());
2955 lines[lines_cache[local_line_no]] = {
2956 line.index,
2957 typename ConstraintLine::Entries(line.entries.begin(),
2958 line.entries.end()),
2959 static_cast<number>(line.inhomogeneity)};
2960 break;
2961
2962 default:
2963 DEAL_II_NOT_IMPLEMENTED();
2964 }
2965 }
2966 }
2967
2968 // check that we set the pointers correctly
2969 for (size_type i = 0; i < lines_cache.size(); ++i)
2970 if (lines_cache[i] != numbers::invalid_size_type)
2971 Assert(i == calculate_line_index(lines[lines_cache[i]].index),
2972 ExcInternalError());
2973 }
2974
2975 // if the object was sorted before, then make sure it is so afterward as
2976 // well. otherwise leave everything in the unsorted state
2977 if (object_was_sorted == true)
2978 close();
2979 }
2980
2981
2982
2983 template <typename number>
2984 template <typename MatrixType>
2985 inline void
2986 AffineConstraints<number>::distribute_local_to_global(
2987 const FullMatrix<number> &local_matrix,
2988 const std::vector<size_type> &local_dof_indices,
2989 MatrixType &global_matrix) const
2990 {
2991 // create a dummy and hand on to the function actually implementing this
2992 // feature in the cm.templates.h file.
2993 Vector<typename MatrixType::value_type> dummy(0);
2994 distribute_local_to_global(
2995 local_matrix,
2996 dummy,
2997 local_dof_indices,
2998 global_matrix,
2999 dummy,
3000 false,
3001 std::integral_constant<
3002 bool,
3003 internal::AffineConstraints::IsBlockMatrix<MatrixType>::value>());
3004 }
3005
3006
3007
3008 template <typename number>
3009 template <typename MatrixType, typename VectorType>
3010 inline void
3011 AffineConstraints<number>::distribute_local_to_global(
3012 const FullMatrix<number> &local_matrix,
3013 const Vector<number> &local_vector,
3014 const std::vector<size_type> &local_dof_indices,
3015 MatrixType &global_matrix,
3016 VectorType &global_vector,
3017 bool use_inhomogeneities_for_rhs) const
3018 {
3019 // enter the internal function with the respective block information set,
3020 // the actual implementation follows in the cm.templates.h file.
3021 distribute_local_to_global(
3022 local_matrix,
3023 local_vector,
3024 local_dof_indices,
3025 global_matrix,
3026 global_vector,
3027 use_inhomogeneities_for_rhs,
3028 std::integral_constant<
3029 bool,
3030 internal::AffineConstraints::IsBlockMatrix<MatrixType>::value>());
3031 }
3032
3033
3034
3035 template <typename number>
3036 inline AffineConstraints<number>::ConstraintLine::ConstraintLine(
3037 const size_type &index,
3038 const typename AffineConstraints<number>::ConstraintLine::Entries &entries,
3039 const number inhomogeneity)
3040 : index(index)
3041 , entries(entries)
3042 , inhomogeneity(inhomogeneity)
3043 {}
3044
3045
3046
3047 DEAL_II_NAMESPACE_CLOSE
3048
3049 #endif