Debian Codegraph @

include/deal.II/lac/vector.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 1999 - 2024 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_vector_h
16 #define dealii_vector_h
17
18
19 #include <deal.II/base/config.h>
20
21 #include <deal.II/base/aligned_vector.h>
22 #include <deal.II/base/exceptions.h>
23 #include <deal.II/base/index_set.h>
24 #include <deal.II/base/numbers.h>
25
26 #include <deal.II/lac/read_vector.h>
27 #include <deal.II/lac/vector_operation.h>
28 #include <deal.II/lac/vector_type_traits.h>
29
30 #include <boost/serialization/split_member.hpp>
31
32 #include <algorithm>
33 #include <initializer_list>
34 #include <iosfwd>
35 #include <vector>
36
37 DEAL_II_NAMESPACE_OPEN
38
39
40 // Forward declarations
41 #ifndef DOXYGEN
42 # ifdef DEAL_II_WITH_PETSC
43 namespace PETScWrappers
44 {
45 class VectorBase;
46 }
47 # endif
48
49 # ifdef DEAL_II_WITH_TRILINOS
50 namespace TrilinosWrappers
51 {
52 namespace MPI
53 {
54 class Vector;
55 }
56 } // namespace TrilinosWrappers
57 # endif
58
59 # ifdef DEAL_II_TRILINOS_WITH_TPETRA
60 namespace LinearAlgebra
61 {
62 namespace TpetraWrappers
63 {
64 template <typename Number, typename MemorySpace>
65 class Vector;
66 }
67 } // namespace LinearAlgebra
68 # endif
69
70 template <typename number>
71 class LAPACKFullMatrix;
72
73 template <typename>
74 class BlockVector;
75
76 namespace parallel
77 {
78 namespace internal
79 {
80 class TBBPartitioner;
81 }
82 } // namespace parallel
83 #endif
84
85
86 /**
87 * @addtogroup Vectors
88 * @{
89 */
90
91 /**
92 * A class that represents a vector of numerical elements. As for the
93 * other classes, in the
94 * @ref Vectors
95 * group, this class has a substantial
96 * number of member functions. These include:
97 * - functions that initialize the vector or change its size;
98 * - functions that compute properties of the vector, such as a variety of
99 * norms;
100 * - functions that allow reading from or writing to individual elements of the
101 * vector;
102 * - functions that implement algebraic operations for vectors, such as
103 * addition of vectors; and
104 * - functions that allow inputting and outputting the data stored by vectors.
105 *
106 * In contrast to the C++ standard library class `std::vector`, this class
107 * intends to implement not simply an array that allows access to its elements,
108 * but indeed a vector that is a member of the mathematical concept of a
109 * "vector space" suitable for numerical computations.
110 *
111 * @note Instantiations for this template are provided for <tt>@<float@>,
112 * @<double@>, @<std::complex@<float@>@>, @<std::complex@<double@>@></tt>;
113 * others can be generated in application programs (see the section on
114 * @ref Instantiations
115 * in the manual).
116 */
117 template <typename Number>
118 class Vector : public ReadVector<Number>
119 {
120 public:
121 /**
122 * This class only supports basic numeric types (i.e., we support double and
123 * float but not automatically differentiated numbers).
124 *
125 * @note we test real_type here to get the underlying scalar type when using
126 * std::complex.
127 */
128 static_assert(
129 std::is_arithmetic_v<typename numbers::NumberTraits<Number>::real_type>,
130 "The Vector class only supports basic numeric types. In particular, it "
131 "does not support automatically differentiated numbers.");
132
133 /**
134 * Declare standard types used in all containers. These types parallel those
135 * in the <tt>C++</tt> standard libraries <tt>vector<...></tt> class.
136 */
137 using value_type = Number;
138 using pointer = value_type *;
139 using const_pointer = const value_type *;
140 using iterator = value_type *;
141 using const_iterator = const value_type *;
142 using reference = value_type &;
143 using const_reference = const value_type &;
144 using size_type = types::global_dof_index;
145
146 /**
147 * Declare a type that has holds real-valued numbers with the same precision
148 * as the template argument to this class. If the template argument of this
149 * class is a real data type, then real_type equals the template argument.
150 * If the template argument is a std::complex type then real_type equals the
151 * type underlying the complex numbers.
152 *
153 * This alias is used to represent the return type of norms.
154 */
155 using real_type = typename numbers::NumberTraits<Number>::real_type;
156
157 /**
158 * @name Basic object handling
159 */
160 /** @{ */
161 /**
162 * Constructor. Create a vector of dimension zero.
163 */
164 Vector();
165
166 /**
167 * Copy constructor. Sets the dimension to that of the given vector, and
168 * copies all elements.
169 *
170 * We would like to make this constructor explicit, but standard containers
171 * insist on using it implicitly.
172 *
173 * @dealiiOperationIsMultithreaded
174 */
175 Vector(const Vector<Number> &v);
176
177 /**
178 * Move constructor. Creates a new vector by stealing the internal data of
179 * the vector @p v.
180 */
181 Vector(Vector<Number> &&v) noexcept = default;
182
183 /**
184 * Copy constructor taking a vector of another data type.
185 *
186 * This constructor will fail to compile if
187 * there is no conversion path from @p OtherNumber to @p Number. You may
188 * lose accuracy when copying to a vector with data elements with
189 * less accuracy.
190 */
191 template <typename OtherNumber>
192 explicit Vector(const Vector<OtherNumber> &v);
193
194 /**
195 * Copy constructor taking an object of type `std::initializer_list`. This
196 * constructor can be used to initialize a vector using a brace-enclosed
197 * list of numbers, such as in the following example:
198 * @code
199 * Vector<double> v({1,2,3});
200 * @endcode
201 * This creates a vector of size 3, whose (double precision) elements have
202 * values 1.0, 2.0, and 3.0.
203 *
204 * This constructor will fail to compile if
205 * there is no conversion path from @p OtherNumber to @p Number. You may
206 * lose accuracy when copying to a vector with data elements with
207 * less accuracy.
208 */
209 template <typename OtherNumber>
210 explicit Vector(const std::initializer_list<OtherNumber> &v);
211
212 #ifdef DEAL_II_WITH_PETSC
213 /**
214 * Another copy constructor: copy the values from a PETSc vector class. This
215 * copy constructor is only available if PETSc was detected during
216 * configuration time.
217 *
218 * Note that due to the communication model used in MPI, this operation can
219 * only succeed if all processes do it at the same time when <code>v</code>
220 * is a distributed vector: It is not possible for only one process to
221 * obtain a copy of a parallel vector while the other jobs do something
222 * else.
223 */
224 explicit Vector(const PETScWrappers::VectorBase &v);
225 #endif
226
227 #ifdef DEAL_II_WITH_TRILINOS
228 /**
229 * Another copy constructor: copy the values from a Trilinos wrapper vector.
230 * This copy constructor is only available if Trilinos was detected during
231 * configuration time.
232 *
233 * @note Due to the communication model used in MPI, this operation can
234 * only succeed if all processes that have knowledge of @p v
235 * (i.e. those given by <code>v.get_mpi_communicator()</code>) do it at
236 * the same time. This means that unless you use a split MPI communicator
237 * then it is not normally possible for only one or a subset of processes
238 * to obtain a copy of a parallel vector while the other jobs do something
239 * else. In other words, calling this function is a @ref GlossCollectiveOperation "collective operation"
240 * that needs to be executed by all MPI processes that jointly share @p v.
241 */
242 explicit Vector(const TrilinosWrappers::MPI::Vector &v);
243 #endif
244
245 #ifdef DEAL_II_TRILINOS_WITH_TPETRA
246 /**
247 * Another copy constructor: copy the values from a Trilinos wrapper vector.
248 * This copy constructor is only available if Trilinos was detected during
249 * configuration time.
250 *
251 * @note Due to the communication model used in MPI, this operation can
252 * only succeed if all processes that have knowledge of @p v
253 * (i.e. those given by <code>v.get_mpi_communicator()</code>) do it at
254 * the same time. This means that unless you use a split MPI communicator
255 * then it is not normally possible for only one or a subset of processes
256 * to obtain a copy of a parallel vector while the other jobs do something
257 * else. In other words, calling this function is a @ref GlossCollectiveOperation "collective operation"
258 * that needs to be executed by all MPI processes that jointly share @p v.
259 */
260 template <typename OtherNumber, typename MemorySpace>
261 explicit Vector(
262 const LinearAlgebra::TpetraWrappers::Vector<OtherNumber, MemorySpace> &v);
263 #endif
264
265 /**
266 * Constructor. Set dimension to @p n and initialize all elements with zero.
267 *
268 * The constructor is made explicit to avoid accidents like this:
269 * <tt>v=0;</tt>. Presumably, the user wants to set every element of the
270 * vector to zero, but instead, what happens is this call:
271 * <tt>v=Vector@<number@>(0);</tt>, i.e. the vector is replaced by one of
272 * length zero.
273 */
274 explicit Vector(const size_type n);
275
276 /**
277 * Initialize the vector with a given range of values pointed to by the
278 * iterators. This function is there in analogy to the @p std::vector class.
279 */
280 template <typename InputIterator>
281 Vector(const InputIterator first, const InputIterator last);
282
283 /**
284 * Destructor, deallocates memory. Made virtual to allow for derived classes
285 * to behave properly.
286 */
287 virtual ~Vector() override = default;
288
289
290 /**
291 * This function is equivalent to writing <code>size() == 0</code>.
292 */
293 bool
294 empty() const;
295
296 /**
297 * This function does nothing but exists for compatibility with the parallel
298 * vector classes.
299 *
300 * For the parallel vector wrapper class, this function compresses the
301 * underlying representation of the vector, i.e. flushes the buffers of the
302 * vector object if it has any. This function is necessary after writing
303 * into a vector element-by-element and before anything else can be done on
304 * it.
305 *
306 * However, for the implementation of this class, it is immaterial and thus
307 * an empty function.
308 */
309 void
310 compress(VectorOperation::values operation = VectorOperation::unknown) const;
311
312 /**
313 * Change the dimension of the vector to @p N. The reserved memory for this
314 * vector remains unchanged if possible, to make things faster; this may
315 * waste some memory, so keep this in mind. However, if <tt>N==0</tt> all
316 * memory is freed, i.e. if you want to resize the vector and release the
317 * memory not needed, you have to first call <tt>reinit(0)</tt> and then
318 * <tt>reinit(N)</tt>. This cited behavior is analogous to that of the
319 * standard library containers.
320 *
321 * If @p omit_zeroing_entries is false, the vector is filled by zeros.
322 * Otherwise, the elements are left an unspecified state.
323 *
324 * This function is virtual in order to allow for derived classes to handle
325 * memory separately.
326 */
327 virtual void
328 reinit(const size_type N, const bool omit_zeroing_entries = false);
329
330 /**
331 * Same as above, but will preserve the values of vector upon resizing.
332 * If we new size is bigger, we will have
333 * \f[
334 * \mathbf V \rightarrow
335 * \left(
336 * \begin{array}{c}
337 * \mathbf V \\
338 * \mathbf 0
339 * \end{array}
340 * \right)
341 * \f]
342 * whereas if the desired size is smaller, then
343 * \f[
344 * \left(
345 * \begin{array}{c}
346 * \mathbf V_1 \\
347 * \mathbf V_2
348 * \end{array}
349 * \right)
350 * \rightarrow \mathbf V_1
351 * \f]
352 */
353 void
354 grow_or_shrink(const size_type N);
355
356 /**
357 * Apply <a href="https://en.wikipedia.org/wiki/Givens_rotation">Givens
358 * rotation</a>
359 * @p csr (a triplet of cosine, sine and radius, see
360 * Utilities::LinearAlgebra::givens_rotation())
361 * to the vector in the plane spanned by the @p i'th and @p k'th unit vectors.
362 */
363 void
364 apply_givens_rotation(const std::array<Number, 3> &csr,
365 const size_type i,
366 const size_type k);
367
368 /**
369 * Change the dimension to that of the vector @p V. The same applies as for
370 * the other @p reinit function.
371 *
372 * The elements of @p V are not copied, i.e. this function is the same as
373 * calling <tt>reinit (V.size(), omit_zeroing_entries)</tt>.
374 */
375 template <typename Number2>
376 void
377 reinit(const Vector<Number2> &V, const bool omit_zeroing_entries = false);
378
379 /**
380 * Swap the contents of this vector and the other vector @p v. One could do
381 * this operation with a temporary variable and copying over the data
382 * elements, but this function is significantly more efficient since it only
383 * swaps the pointers to the data of the two vectors and therefore does not
384 * need to allocate temporary storage and move data around.
385 *
386 * This function is analogous to the @p swap function of all C++
387 * standard containers. Also, there is a global function <tt>swap(u,v)</tt>
388 * that simply calls <tt>u.swap(v)</tt>, again in analogy to standard
389 * functions.
390 *
391 * This function is virtual in order to allow for derived classes to handle
392 * memory separately.
393 */
394 virtual void
395 swap(Vector<Number> &v) noexcept;
396
397 /**
398 * Set all components of the vector to the given number @p s.
399 *
400 * Since the semantics of assigning a scalar to a vector are not immediately
401 * clear, this operator should really only be used if you want to set the
402 * entire vector to zero. This allows the intuitive notation <tt>v=0</tt>.
403 * Assigning other values is deprecated and may be disallowed in the future.
404 *
405 * @dealiiOperationIsMultithreaded
406 */
407 Vector<Number> &
408 operator=(const Number s);
409
410 /**
411 * Copy the given vector. Resize the present vector if necessary.
412 *
413 * @dealiiOperationIsMultithreaded
414 */
415 Vector<Number> &
416 operator=(const Vector<Number> &v);
417
418 /**
419 * Move the given vector. This operator replaces the present vector with
420 * the internal data of the vector @p v and resets @p v to the state it would
421 * have after being newly default-constructed.
422 */
423 Vector<Number> &
424 operator=(Vector<Number> &&v) noexcept = default;
425
426 /**
427 * Copy the given vector. Resize the present vector if necessary.
428 *
429 * @dealiiOperationIsMultithreaded
430 */
431 template <typename Number2>
432 Vector<Number> &
433 operator=(const Vector<Number2> &v);
434
435 /**
436 * Copy operator for assigning a block vector to a regular vector.
437 */
438 Vector<Number> &
439 operator=(const BlockVector<Number> &v);
440
441 #ifdef DEAL_II_WITH_PETSC
442 /**
443 * Another copy operator: copy the values from a PETSc wrapper vector
444 * class. This operator is only available if PETSc was detected during
445 * configuration time.
446 *
447 * Note that due to the communication model used in MPI, this operation can
448 * only succeed if all processes do it at the same time when <code>v</code>
449 * is a distributed vector: It is not possible for only one process to
450 * obtain a copy of a parallel vector while the other jobs do something
451 * else.
452 */
453 Vector<Number> &
454 operator=(const PETScWrappers::VectorBase &v);
455 #endif
456
457
458 #ifdef DEAL_II_WITH_TRILINOS
459 /**
460 * Another copy operator: copy the values from a (sequential or parallel,
461 * depending on the underlying compiler) Trilinos wrapper vector class. This
462 * operator is only available if Trilinos was detected during configuration
463 * time.
464 *
465 * @note Due to the communication model used in MPI, this operation can
466 * only succeed if all processes that have knowledge of @p v
467 * (i.e. those given by <code>v.get_mpi_communicator()</code>) do it at
468 * the same time. This means that unless you use a split MPI communicator
469 * then it is not normally possible for only one or a subset of processes
470 * to obtain a copy of a parallel vector while the other jobs do something
471 * else. In other words, calling this function is a @ref GlossCollectiveOperation "collective operation"
472 * that needs to be executed by all MPI processes that jointly share @p v.
473 */
474 Vector<Number> &
475 operator=(const TrilinosWrappers::MPI::Vector &v);
476 #endif
477
478 #ifdef DEAL_II_TRILINOS_WITH_TPETRA
479 /**
480 * Another copy operator: copy the values from a (sequential or parallel,
481 * depending on the underlying compiler) Trilinos wrapper vector class. This
482 * operator is only available if Trilinos was detected during configuration
483 * time.
484 *
485 * @note Due to the communication model used in MPI, this operation can
486 * only succeed if all processes that have knowledge of @p v
487 * (i.e. those given by <code>v.get_mpi_communicator()</code>) do it at
488 * the same time. This means that unless you use a split MPI communicator
489 * then it is not normally possible for only one or a subset of processes
490 * to obtain a copy of a parallel vector while the other jobs do something
491 * else. In other words, calling this function is a @ref GlossCollectiveOperation "collective operation"
492 * that needs to be executed by all MPI processes that jointly share @p v.
493 */
494 template <typename OtherNumber, typename MemorySpace>
495 Vector<Number> &
496 operator=(
497 const LinearAlgebra::TpetraWrappers::Vector<OtherNumber, MemorySpace> &v);
498 #endif
499
500 /**
501 * Test for equality. This function assumes that the present vector and the
502 * one to compare with have the same size already, since comparing vectors
503 * of different sizes makes not much sense anyway.
504 */
505 template <typename Number2>
506 bool
507 operator==(const Vector<Number2> &v) const;
508
509 /**
510 * Test for inequality. This function assumes that the present vector and
511 * the one to compare with have the same size already, since comparing
512 * vectors of different sizes makes not much sense anyway.
513 */
514 template <typename Number2>
515 bool
516 operator!=(const Vector<Number2> &v) const;
517
518 /** @} */
519
520
521 /**
522 * @name Scalar products, norms and related operations
523 */
524 /** @{ */
525
526 /**
527 * Return the scalar product of two vectors. The return type is the
528 * underlying type of @p this vector, so the return type and the accuracy
529 * with which it the result is computed depend on the order of the arguments
530 * of this vector.
531 *
532 * For complex vectors, the scalar product is implemented as
533 * $\left<v,w\right>=\sum_i v_i \bar{w_i}$.
534 *
535 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
536 * with the same order of summation in every run, which gives fully
537 * repeatable results from one run to another.
538 */
539 template <typename Number2>
540 Number
541 operator*(const Vector<Number2> &V) const;
542
543 /**
544 * Return the square of the $l_2$-norm.
545 *
546 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
547 * with the same order of summation in every run, which gives fully
548 * repeatable results from one run to another.
549 */
550 real_type
551 norm_sqr() const;
552
553 /**
554 * Mean value of the elements of this vector.
555 *
556 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
557 * with the same order of summation in every run, which gives fully
558 * repeatable results from one run to another.
559 */
560 Number
561 mean_value() const;
562
563 /**
564 * $l_1$-norm of the vector. The sum of the absolute values.
565 *
566 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
567 * with the same order of summation in every run, which gives fully
568 * repeatable results from one run to another.
569 */
570 real_type
571 l1_norm() const;
572
573 /**
574 * $l_2$-norm of the vector. The square root of the sum of the squares of
575 * the elements.
576 *
577 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
578 * with the same order of summation in every run, which gives fully
579 * repeatable results from one run to another.
580 */
581 real_type
582 l2_norm() const;
583
584 /**
585 * $l_p$-norm of the vector. The pth root of the sum of the pth powers of
586 * the absolute values of the elements.
587 *
588 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
589 * with the same order of summation in every run, which gives fully
590 * repeatable results from one run to another.
591 */
592 real_type
593 lp_norm(const real_type p) const;
594
595 /**
596 * Maximum absolute value of the elements.
597 */
598 real_type
599 linfty_norm() const;
600
601 /**
602 * Performs a combined operation of a vector addition and a subsequent inner
603 * product, returning the value of the inner product. In other words, the
604 * result of this function is the same as if the user called
605 * @code
606 * this->add(a, V);
607 * return_value = *this * W;
608 * @endcode
609 *
610 * The reason this function exists is that this operation involves less
611 * memory transfer than calling the two functions separately. This method
612 * only needs to load three vectors, @p this, @p V, @p W, whereas calling
613 * separate methods means to load the calling vector @p this twice. Since
614 * most vector operations are memory transfer limited, this reduces the time
615 * by 25\% (or 50\% if @p W equals @p this).
616 *
617 * For complex-valued vectors, the scalar product in the second step is
618 * implemented as
619 * $\left<v,w\right>=\sum_i v_i \bar{w_i}$.
620 *
621 * @dealiiOperationIsMultithreaded The algorithm uses pairwise summation
622 * with the same order of summation in every run, which gives fully
623 * repeatable results from one run to another.
624 */
625 Number
626 add_and_dot(const Number a, const Vector<Number> &V, const Vector<Number> &W);
627
628 /** @} */
629
630
631 /**
632 * @name Data access
633 */
634 /** @{ */
635
636 /**
637 * Return a pointer to the underlying data buffer.
638 */
639 pointer
640 data();
641
642 /**
643 * Return a const pointer to the underlying data buffer.
644 */
645 const_pointer
646 data() const;
647
648 /**
649 * Make the @p Vector class a bit like the <tt>vector<></tt> class of the
650 * C++ standard library by returning iterators to the start and end of the
651 * elements of this vector.
652 */
653 iterator
654 begin();
655
656 /**
657 * Return constant iterator to the start of the vectors.
658 */
659 const_iterator
660 begin() const;
661
662 /**
663 * Return an iterator pointing to the element past the end of the array.
664 */
665 iterator
666 end();
667
668 /**
669 * Return a constant iterator pointing to the element past the end of the
670 * array.
671 */
672 const_iterator
673 end() const;
674
675 /**
676 * Access the value of the @p ith component.
677 */
678 Number
679 operator()(const size_type i) const;
680
681 /**
682 * Access the @p ith component as a writeable reference.
683 */
684 Number &
685 operator()(const size_type i);
686
687 /**
688 * Access the value of the @p ith component.
689 *
690 * Exactly the same as operator().
691 */
692 Number
693 operator[](const size_type i) const;
694
695 /**
696 * Access the @p ith component as a writeable reference.
697 *
698 * Exactly the same as operator().
699 */
700 Number &
701 operator[](const size_type i);
702
703 /**
704 * Instead of getting individual elements of a vector via operator(),
705 * this function allows getting a whole set of elements at once. The
706 * indices of the elements to be read are stated in the first argument, the
707 * corresponding values are returned in the second.
708 *
709 * If the current vector is called @p v, then this function is the equivalent
710 * to the code
711 * @code
712 * for (unsigned int i = 0; i < indices.size(); ++i)
713 * values[i] = v[indices[i]];
714 * @endcode
715 *
716 * @pre The sizes of the @p indices and @p values arrays must be identical.
717 */
718 template <typename OtherNumber>
719 void
720 extract_subvector_to(const std::vector<size_type> &indices,
721 std::vector<OtherNumber> &values) const;
722
723 /**
724 * Extract a range of elements all at once.
725 */
726 virtual void
727 extract_subvector_to(const ArrayView<const types::global_dof_index> &indices,
728 const ArrayView<Number> &elements) const override;
729
730 /**
731 * Instead of getting individual elements of a vector via operator(),
732 * this function allows getting a whole set of elements at once. In
733 * contrast to the previous function, this function obtains the
734 * indices of the elements by dereferencing all elements of the iterator
735 * range provided by the first two arguments, and puts the vector
736 * values into memory locations obtained by dereferencing a range
737 * of iterators starting at the location pointed to by the third
738 * argument.
739 *
740 * If the current vector is called @p v, then this function is the equivalent
741 * to the code
742 * @code
743 * ForwardIterator indices_p = indices_begin;
744 * OutputIterator values_p = values_begin;
745 * while (indices_p != indices_end)
746 * {
747 * *values_p = v[*indices_p];
748 * ++indices_p;
749 * ++values_p;
750 * }
751 * @endcode
752 *
753 * @pre It must be possible to write into as many memory locations
754 * starting at @p values_begin as there are iterators between
755 * @p indices_begin and @p indices_end.
756 */
757 template <typename ForwardIterator, typename OutputIterator>
758 void
759 extract_subvector_to(ForwardIterator indices_begin,
760 const ForwardIterator indices_end,
761 OutputIterator values_begin) const;
762 /** @} */
763
764
765 /**
766 * @name Modification of vectors
767 */
768 /** @{ */
769
770 /**
771 * Add the given vector to the present one.
772 *
773 * @dealiiOperationIsMultithreaded
774 */
775 Vector<Number> &
776 operator+=(const Vector<Number> &V);
777
778 /**
779 * Subtract the given vector from the present one.
780 *
781 * @dealiiOperationIsMultithreaded
782 */
783 Vector<Number> &
784 operator-=(const Vector<Number> &V);
785
786 /**
787 * A collective add operation: This function adds a whole set of values
788 * stored in @p values to the vector components specified by @p indices.
789 */
790 template <typename OtherNumber>
791 void
792 add(const std::vector<size_type> &indices,
793 const std::vector<OtherNumber> &values);
794
795 /**
796 * This is a second collective add operation. As a difference, this function
797 * takes a deal.II vector of values.
798 */
799 template <typename OtherNumber>
800 void
801 add(const std::vector<size_type> &indices, const Vector<OtherNumber> &values);
802
803 /**
804 * Take an address where <tt>n_elements</tt> are stored contiguously and add
805 * them into the vector. Handles all cases which are not covered by the
806 * other two <tt>add()</tt> functions above.
807 */
808 template <typename OtherNumber>
809 void
810 add(const size_type n_elements,
811 const size_type *indices,
812 const OtherNumber *values);
813
814 /**
815 * Addition of @p s to all components. Note that @p s is a scalar and not a
816 * vector.
817 *
818 * @dealiiOperationIsMultithreaded
819 */
820 void
821 add(const Number s);
822
823 /**
824 * Multiple addition of scaled vectors, i.e. <tt>*this += a*V+b*W</tt>.
825 *
826 * @dealiiOperationIsMultithreaded
827 */
828 void
829 add(const Number a,
830 const Vector<Number> &V,
831 const Number b,
832 const Vector<Number> &W);
833
834 /**
835 * Simple addition of a multiple of a vector, i.e. <tt>*this += a*V</tt>.
836 *
837 * @dealiiOperationIsMultithreaded
838 */
839 void
840 add(const Number a, const Vector<Number> &V);
841
842 /**
843 * Scaling and simple vector addition, i.e. <tt>*this = s*(*this)+V</tt>.
844 *
845 * @dealiiOperationIsMultithreaded
846 */
847 void
848 sadd(const Number s, const Vector<Number> &V);
849
850 /**
851 * Scaling and simple addition, i.e. <tt>*this = s*(*this)+a*V</tt>.
852 *
853 * @dealiiOperationIsMultithreaded
854 */
855 void
856 sadd(const Number s, const Number a, const Vector<Number> &V);
857
858 /**
859 * Scale each element of the vector by a constant value.
860 *
861 * @dealiiOperationIsMultithreaded
862 */
863 Vector<Number> &
864 operator*=(const Number factor);
865
866 /**
867 * Scale each element of the vector by the inverse of the given value.
868 *
869 * @dealiiOperationIsMultithreaded
870 */
871 Vector<Number> &
872 operator/=(const Number factor);
873
874 /**
875 * Scale each element of this vector by the corresponding element in the
876 * argument. This function is mostly meant to simulate multiplication (and
877 * immediate re-assignment) by a diagonal scaling matrix.
878 *
879 * @dealiiOperationIsMultithreaded
880 */
881 void
882 scale(const Vector<Number> &scaling_factors);
883
884 /**
885 * Scale each element of this vector by the corresponding element in the
886 * argument. This function is mostly meant to simulate multiplication (and
887 * immediate re-assignment) by a diagonal scaling matrix.
888 */
889 template <typename Number2>
890 void
891 scale(const Vector<Number2> &scaling_factors);
892
893 /**
894 * Assignment <tt>*this = a*u</tt>.
895 *
896 * @dealiiOperationIsMultithreaded
897 */
898 void
899 equ(const Number a, const Vector<Number> &u);
900
901 /**
902 * Assignment <tt>*this = a*u</tt>.
903 */
904 template <typename Number2>
905 void
906 equ(const Number a, const Vector<Number2> &u);
907
908 /**
909 * This function does nothing but exists for compatibility with the @p
910 * parallel vector classes (e.g., LinearAlgebra::distributed::Vector class).
911 */
912 void
913 update_ghost_values() const;
914 /** @} */
915
916
917 /**
918 * @name Input and output
919 */
920 /** @{ */
921 /**
922 * Print to a stream. @p precision denotes the desired precision with which
923 * values shall be printed, @p scientific whether scientific notation shall
924 * be used. If @p across is @p true then the vector is printed in a line,
925 * while if @p false then the elements are printed on a separate line each.
926 */
927 void
928 print(std::ostream &out,
929 const unsigned int precision = 3,
930 const bool scientific = true,
931 const bool across = true) const;
932
933 /**
934 * Write the vector en bloc to a file. This is done in a binary mode, so the
935 * output is neither readable by humans nor (probably) by other computers
936 * using a different operating system or number format.
937 */
938 void
939 block_write(std::ostream &out) const;
940
941 /**
942 * Read a vector en block from a file. This is done using the inverse
943 * operations to the above function, so it is reasonably fast because the
944 * bitstream is not interpreted.
945 *
946 * The vector is resized if necessary.
947 *
948 * A primitive form of error checking is performed which will recognize the
949 * bluntest attempts to interpret some data as a vector stored bitwise to a
950 * file, but not more.
951 */
952 void
953 block_read(std::istream &in);
954
955 /**
956 * Write the data of this object to a stream for the purpose of
957 * serialization using the [BOOST serialization
958 * library](https://www.boost.org/doc/libs/1_74_0/libs/serialization/doc/index.html).
959 */
960 template <class Archive>
961 void
962 save(Archive &ar, const unsigned int version) const;
963
964 /**
965 * Read the data of this object from a stream for the purpose of
966 * serialization using the [BOOST serialization
967 * library](https://www.boost.org/doc/libs/1_74_0/libs/serialization/doc/index.html).
968 */
969 template <class Archive>
970 void
971 load(Archive &ar, const unsigned int version);
972
973 #ifdef DOXYGEN
974 /**
975 * Write and read the data of this object from a stream for the purpose
976 * of serialization using the [BOOST serialization
977 * library](https://www.boost.org/doc/libs/1_74_0/libs/serialization/doc/index.html).
978 */
979 template <class Archive>
980 void
981 serialize(Archive &archive, const unsigned int version);
982 #else
983 // This macro defines the serialize() method that is compatible with
984 // the templated save() and load() method that have been implemented.
985 BOOST_SERIALIZATION_SPLIT_MEMBER()
986 #endif
987
988 /**
989 * @}
990 */
991
992 /**
993 * @name Information about the object
994 */
995 /** @{ */
996
997 /**
998 * Return true if the given global index is in the local range of this
999 * processor. Since this is not a distributed vector the method always
1000 * returns true.
1001 */
1002 bool
1003 in_local_range(const size_type global_index) const;
1004
1005 /**
1006 * Return an index set that describes which elements of this vector are
1007 * owned by the current processor. Note that this index set does not include
1008 * elements this vector may store locally as ghost elements but that are in
1009 * fact owned by another processor. As a consequence, the index sets
1010 * returned on different processors if this is a distributed vector will
1011 * form disjoint sets that add up to the complete index set. Obviously, if a
1012 * vector is created on only one processor, then the result would satisfy
1013 * @code
1014 * vec.locally_owned_elements() == complete_index_set (vec.size())
1015 * @endcode
1016 *
1017 * Since the current data type does not support parallel data storage across
1018 * different processors, the returned index set is the complete index set.
1019 */
1020 IndexSet
1021 locally_owned_elements() const;
1022
1023 /**
1024 * Return dimension of the vector.
1025 */
1026 virtual size_type
1027 size() const override;
1028
1029 /**
1030 * Return local dimension of the vector. Since this vector does not support
1031 * distributed data this is always the same value as size().
1032 *
1033 * @note This function exists for compatibility with
1034 * LinearAlgebra::ReadWriteVector.
1035 */
1036 size_type
1037 locally_owned_size() const;
1038
1039 /**
1040 * Return whether the vector contains only elements with value zero. This
1041 * function is mainly for internal consistency checks and should seldom be
1042 * used when not in debug mode since it uses quite some time.
1043 */
1044 bool
1045 all_zero() const;
1046
1047 /**
1048 * Return @p true if the vector has no negative entries, i.e. all entries
1049 * are zero or positive. This function is used, for example, to check
1050 * whether refinement indicators are really all positive (or zero).
1051 *
1052 * The function obviously only makes sense if the template argument of this
1053 * class is a real type. If it is a complex type, then an exception is
1054 * thrown.
1055 */
1056 bool
1057 is_non_negative() const;
1058
1059 /**
1060 * Determine an estimate for the memory consumption (in bytes) of this
1061 * object.
1062 */
1063 std::size_t
1064 memory_consumption() const;
1065
1066 /**
1067 * This function exists for compatibility with the @p
1068 * parallel vector classes (e.g., LinearAlgebra::distributed::Vector class)
1069 * and always returns false since this implementation is serial.
1070 */
1071 bool
1072 has_ghost_elements() const;
1073
1074 /**
1075 * This function exists for compatibility with the @p
1076 * parallel vector classes (e.g., LinearAlgebra::distributed::Vector class)
1077 * and does nothing since this implementation is serial.
1078 */
1079 void
1080 zero_out_ghost_values() const;
1081
1082 /**
1083 * This function returns the empty object MPI_COMM_SELF that does not signal
1084 * any parallel communication model, as this vector is in fact serial with
1085 * respect to the message passing interface (MPI). The function exists for
1086 * compatibility with the @p parallel vector classes (e.g.,
1087 * LinearAlgebra::distributed::Vector class).
1088 */
1089 MPI_Comm
1090 get_mpi_communicator() const;
1091 /** @} */
1092
1093 private:
1094 /**
1095 * Array of elements owned by this vector.
1096 */
1097 AlignedVector<Number> values;
1098
1099 /**
1100 * Convenience function used at the end of initialization or
1101 * reinitialization. Resets (if necessary) the loop partitioner to the
1102 * correct state, based on its current state and the length of the vector.
1103 */
1104 void
1105 maybe_reset_thread_partitioner();
1106
1107 /**
1108 * Actual implementation of the reinit functions.
1109 */
1110 void
1111 do_reinit(const size_type new_size,
1112 const bool omit_zeroing_entries,
1113 const bool reset_partitioner);
1114
1115 /**
1116 * For parallel loops with TBB, this member variable stores the affinity
1117 * information of loops.
1118 */
1119 mutable std::shared_ptr<parallel::internal::TBBPartitioner>
1120 thread_loop_partitioner;
1121
1122 // Make all other vector types friends.
1123 template <typename Number2>
1124 friend class Vector;
1125 };
1126
1127 /** @} */
1128 /*----------------------- Inline functions ----------------------------------*/
1129
1130
1131 #ifndef DOXYGEN
1132
1133
1134 //------------------------ declarations for explicit specializations
1135 template <>
1136 Vector<int>::real_type
1137 Vector<int>::lp_norm(const real_type) const;
1138
1139
1140 //------------------------ inline functions
1141
1142 template <typename Number>
1143 inline Vector<Number>::Vector()
1144 {
1145 // virtual functions called in constructors and destructors never use the
1146 // override in a derived class
1147 // for clarity be explicit on which function is called
1148 Vector<Number>::reinit(0);
1149 }
1150
1151
1152
1153 template <typename Number>
1154 template <typename OtherNumber>
1155 Vector<Number>::Vector(const std::initializer_list<OtherNumber> &v)
1156 : Vector(v.begin(), v.end())
1157 {}
1158
1159
1160
1161 template <typename Number>
1162 template <typename InputIterator>
1163 Vector<Number>::Vector(const InputIterator first, const InputIterator last)
1164 {
1165 // allocate memory. do not initialize it, as we will copy over to it in a
1166 // second
1167 reinit(std::distance(first, last), true);
1168 std::copy(first, last, begin());
1169 }
1170
1171
1172
1173 template <typename Number>
1174 inline Vector<Number>::Vector(const size_type n)
1175 {
1176 // virtual functions called in constructors and destructors never use the
1177 // override in a derived class
1178 // for clarity be explicit on which function is called
1179 Vector<Number>::reinit(n, false);
1180 }
1181
1182
1183
1184 template <typename Number>
1185 inline typename Vector<Number>::size_type
1186 Vector<Number>::size() const
1187 {
1188 return values.size();
1189 }
1190
1191
1192
1193 template <typename Number>
1194 inline typename Vector<Number>::size_type
1195 Vector<Number>::locally_owned_size() const
1196 {
1197 return values.size();
1198 }
1199
1200
1201
1202 template <typename Number>
1203 inline bool
1204 Vector<Number>::in_local_range(const size_type) const
1205 {
1206 return true;
1207 }
1208
1209
1210
1211 template <typename Number>
1212 inline typename Vector<Number>::pointer
1213 Vector<Number>::data()
1214 {
1215 return values.data();
1216 }
1217
1218
1219
1220 template <typename Number>
1221 inline typename Vector<Number>::const_pointer
1222 Vector<Number>::data() const
1223 {
1224 return values.data();
1225 }
1226
1227
1228
1229 template <typename Number>
1230 inline typename Vector<Number>::iterator
1231 Vector<Number>::begin()
1232 {
1233 return values.begin();
1234 }
1235
1236
1237
1238 template <typename Number>
1239 inline typename Vector<Number>::const_iterator
1240 Vector<Number>::begin() const
1241 {
1242 return values.begin();
1243 }
1244
1245
1246
1247 template <typename Number>
1248 inline typename Vector<Number>::iterator
1249 Vector<Number>::end()
1250 {
1251 return values.end();
1252 }
1253
1254
1255
1256 template <typename Number>
1257 inline typename Vector<Number>::const_iterator
1258 Vector<Number>::end() const
1259 {
1260 return values.end();
1261 }
1262
1263
1264
1265 template <typename Number>
1266 inline Number
1267 Vector<Number>::operator()(const size_type i) const
1268 {
1269 AssertIndexRange(i, size());
1270 return values[i];
1271 }
1272
1273
1274
1275 template <typename Number>
1276 inline Number &
1277 Vector<Number>::operator()(const size_type i)
1278 {
1279 AssertIndexRange(i, size());
1280 return values[i];
1281 }
1282
1283
1284
1285 template <typename Number>
1286 inline Number
1287 Vector<Number>::operator[](const size_type i) const
1288 {
1289 return operator()(i);
1290 }
1291
1292
1293
1294 template <typename Number>
1295 inline Number &
1296 Vector<Number>::operator[](const size_type i)
1297 {
1298 return operator()(i);
1299 }
1300
1301
1302
1303 template <typename Number>
1304 template <typename OtherNumber>
1305 inline void
1306 Vector<Number>::extract_subvector_to(const std::vector<size_type> &indices,
1307 std::vector<OtherNumber> &values) const
1308 {
1309 for (size_type i = 0; i < indices.size(); ++i)
1310 values[i] = operator()(indices[i]);
1311 }
1312
1313
1314
1315 template <typename Number>
1316 template <typename ForwardIterator, typename OutputIterator>
1317 inline void
1318 Vector<Number>::extract_subvector_to(ForwardIterator indices_begin,
1319 const ForwardIterator indices_end,
1320 OutputIterator values_begin) const
1321 {
1322 while (indices_begin != indices_end)
1323 {
1324 *values_begin = operator()(*indices_begin);
1325 ++indices_begin;
1326 ++values_begin;
1327 }
1328 }
1329
1330
1331
1332 template <typename Number>
1333 inline Vector<Number> &
1334 Vector<Number>::operator/=(const Number factor)
1335 {
1336 AssertIsFinite(factor);
1337 Assert(factor != Number(0.), ExcZero());
1338
1339 this->operator*=(Number(1.) / factor);
1340 return *this;
1341 }
1342
1343
1344
1345 template <typename Number>
1346 template <typename OtherNumber>
1347 inline void
1348 Vector<Number>::add(const std::vector<size_type> &indices,
1349 const std::vector<OtherNumber> &values)
1350 {
1351 Assert(indices.size() == values.size(),
1352 ExcDimensionMismatch(indices.size(), values.size()));
1353 add(indices.size(), indices.data(), values.data());
1354 }
1355
1356
1357
1358 template <typename Number>
1359 template <typename OtherNumber>
1360 inline void
1361 Vector<Number>::add(const std::vector<size_type> &indices,
1362 const Vector<OtherNumber> &values)
1363 {
1364 Assert(indices.size() == values.size(),
1365 ExcDimensionMismatch(indices.size(), values.size()));
1366 add(indices.size(), indices.data(), values.values.begin());
1367 }
1368
1369
1370
1371 template <typename Number>
1372 template <typename OtherNumber>
1373 inline void
1374 Vector<Number>::add(const size_type n_indices,
1375 const size_type *indices,
1376 const OtherNumber *values)
1377 {
1378 for (size_type i = 0; i < n_indices; ++i)
1379 {
1380 AssertIndexRange(indices[i], size());
1381 Assert(
1382 numbers::is_finite(values[i]),
1383 ExcMessage(
1384 "The given value is not finite but either infinite or Not A Number (NaN)"));
1385
1386 this->values[indices[i]] += values[i];
1387 }
1388 }
1389
1390
1391
1392 template <typename Number>
1393 template <typename Number2>
1394 inline bool
1395 Vector<Number>::operator!=(const Vector<Number2> &v) const
1396 {
1397 return !(*this == v);
1398 }
1399
1400
1401 template <typename Number>
1402 inline bool
1403 Vector<Number>::empty() const
1404 {
1405 return this->size() == 0;
1406 }
1407
1408 template <typename Number>
1409 inline void
1410 Vector<Number>::compress(VectorOperation::values) const
1411 {}
1412
1413
1414
1415 template <typename Number>
1416 inline bool
1417 Vector<Number>::has_ghost_elements() const
1418 {
1419 return false;
1420 }
1421
1422
1423
1424 template <typename Number>
1425 inline void
1426 Vector<Number>::zero_out_ghost_values() const
1427 {}
1428
1429
1430
1431 template <typename Number>
1432 inline void
1433 Vector<Number>::update_ghost_values() const
1434 {}
1435
1436
1437
1438 template <typename Number>
1439 inline MPI_Comm
1440 Vector<Number>::get_mpi_communicator() const
1441 {
1442 return MPI_COMM_SELF;
1443 }
1444
1445
1446 template <typename Number>
1447 template <typename Number2>
1448 inline void
1449 Vector<Number>::reinit(const Vector<Number2> &v,
1450 const bool omit_zeroing_entries)
1451 {
1452 // go to actual reinit functions in case we need to change something with
1453 // the vector, else there is nothing to be done
1454 if (!omit_zeroing_entries || size() != v.size())
1455 {
1456 do_reinit(v.size(), omit_zeroing_entries, false);
1457 thread_loop_partitioner = v.thread_loop_partitioner;
1458 }
1459 }
1460
1461
1462
1463 // Moved from vector.templates.h as an inline function by Luca Heltai
1464 // on 2009/04/12 to prevent strange compiling errors, after making
1465 // swap virtual.
1466 template <typename Number>
1467 inline void
1468 Vector<Number>::swap(Vector<Number> &v) noexcept
1469 {
1470 values.swap(v.values);
1471 std::swap(thread_loop_partitioner, v.thread_loop_partitioner);
1472 }
1473
1474
1475
1476 template <typename Number>
1477 template <class Archive>
1478 inline void
1479 Vector<Number>::save(Archive &ar, const unsigned int) const
1480 {
1481 // forward to serialization function in the base class.
1482 ar &static_cast<const EnableObserverPointer &>(*this);
1483 ar &values;
1484 }
1485
1486
1487
1488 template <typename Number>
1489 template <class Archive>
1490 inline void
1491 Vector<Number>::load(Archive &ar, const unsigned int)
1492 {
1493 // the load stuff again from the archive
1494 ar &static_cast<EnableObserverPointer &>(*this);
1495 ar &values;
1496 maybe_reset_thread_partitioner();
1497 }
1498
1499 #endif
1500
1501
1502 /**
1503 * @addtogroup Vectors
1504 * @{
1505 */
1506
1507
1508 /**
1509 * Global function @p swap which overloads the default implementation of the
1510 * C++ standard library which uses a temporary object. The function simply
1511 * exchanges the data of the two vectors.
1512 *
1513 * @relatesalso Vector
1514 */
1515 template <typename Number>
1516 inline void
1517 swap(Vector<Number> &u, Vector<Number> &v) noexcept
1518 {
1519 u.swap(v);
1520 }
1521
1522
1523 /**
1524 * Output operator writing a vector to a stream. This operator outputs the
1525 * elements of the vector one by one, with a space between entries. Each entry
1526 * is formatted according to the flags set on the output stream.
1527 *
1528 * @relatesalso Vector
1529 */
1530 template <typename number>
1531 inline std::ostream &
1532 operator<<(std::ostream &out, const Vector<number> &v)
1533 {
1534 Assert(v.size() != 0, ExcEmptyObject());
1535 AssertThrow(out.fail() == false, ExcIO());
1536
1537 for (typename Vector<number>::size_type i = 0; i < v.size() - 1; ++i)
1538 out << v(i) << ' ';
1539 out << v(v.size() - 1);
1540
1541 AssertThrow(out.fail() == false, ExcIO());
1542
1543 return out;
1544 }
1545
1546 /** @} */
1547
1548
1549 /**
1550 * Declare Vector<Number> as serial vector.
1551 *
1552 * @relatesalso Vector
1553 */
1554 template <typename Number>
1555 struct is_serial_vector<Vector<Number>> : std::true_type
1556 {};
1557
1558
1559 DEAL_II_NAMESPACE_CLOSE
1560
1561 #endif