version GIT relicensing-7278-g091132d5eb 2026-12-02 03:10:01+00:00
\(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\)
Loading...
Searching...
No Matches
solver_gmres.h
Go to the documentation of this file.
1// -----------------------------------------------------------------------------
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception OR LGPL-2.1-or-later
4// Copyright (C) 1999 - 2026 by the deal.II authors
5//
6// This file is part of the deal.II library.
7//
8// Detailed license information governing the source code and contributions
9// can be found in LICENSE.md and CONTRIBUTING.md at the top level directory.
10//
11// -----------------------------------------------------------------------------
12
13#ifndef dealii_solver_gmres_h
14#define dealii_solver_gmres_h
15
16
17
18#include <deal.II/base/config.h>
19
23
28#include <deal.II/lac/solver.h>
30#include <deal.II/lac/vector.h>
31
32#include <boost/signals2/signal.hpp>
33
34#include <algorithm>
35#include <cmath>
36#include <complex>
37#include <limits>
38#include <memory>
39#include <utility>
40#include <vector>
41
43
44// forward declarations
45#ifndef DOXYGEN
46namespace LinearAlgebra
47{
48 namespace distributed
49 {
50 template <typename, typename>
51 class Vector;
52 } // namespace distributed
53} // namespace LinearAlgebra
54#endif
55
61namespace internal
62{
66 namespace SolverGMRESImplementation
67 {
73 template <typename Number>
74 struct DeviceData;
75
80 template <typename Number>
82 {
86 std::vector<const Number *> vector_ptrs;
87
92 std::shared_ptr<DeviceData<Number>> device_data;
93 };
94
99 template <typename VectorType>
101 {
102 public:
107 TmpVectors(const unsigned int max_size, VectorMemory<VectorType> &vmem);
108
112 ~TmpVectors() = default;
113
118 VectorType &
119 operator[](const unsigned int i) const;
120
127 VectorType &
128 operator()(const unsigned int i, const VectorType &temp);
129
134 unsigned int
135 size() const;
136
137
138 private:
143
147 std::vector<typename VectorMemory<VectorType>::Pointer> data;
148 };
149
150
151
161 template <typename Number>
163 {
164 public:
169 void
172 const unsigned int max_basis_size,
173 const bool force_reorthogonalization);
174
197 template <typename VectorType>
198 double
200 const unsigned int n,
201 TmpVectors<VectorType> &orthogonal_vectors,
202 const unsigned int accumulated_iterations = 0,
203 const boost::signals2::signal<void(int)> &reorthogonalize_signal =
204 boost::signals2::signal<void(int)>());
205
213 const Vector<double> &
214 solve_projected_system(const bool orthogonalization_finished);
215
220 const FullMatrix<double> &
222
229
230 private:
235
242
247 std::vector<std::pair<double, double>> givens_rotations;
248
253
259
264
274
279
307 double
308 do_givens_rotation(const bool delayed_reorthogonalization,
309 const int col,
310 FullMatrix<double> &matrix,
311 std::vector<std::pair<double, double>> &rotations,
312 Vector<double> &rhs);
313 };
314 } // namespace SolverGMRESImplementation
315} // namespace internal
316
317
318
438template <typename VectorType = Vector<double>>
440class SolverGMRES : public SolverBase<VectorType>
441{
442public:
447 {
458 explicit AdditionalData(const unsigned int max_basis_size = 30,
459 const bool right_preconditioning = false,
460 const bool use_default_residual = true,
461 const bool force_re_orthogonalization = false,
462 const bool batched_mode = false,
464 orthogonalization_strategy =
466 delayed_classical_gram_schmidt);
467
479 unsigned int max_n_tmp_vectors;
480
488 unsigned int max_basis_size;
489
498
503
511
524
529 };
530
537
543
548
552 template <typename MatrixType, typename PreconditionerType>
556 void solve(const MatrixType &A,
557 VectorType &x,
558 const VectorType &b,
559 const PreconditionerType &preconditioner);
560
567 boost::signals2::connection
568 connect_condition_number_slot(const std::function<void(double)> &slot,
569 const bool every_iteration = false);
570
577 boost::signals2::connection
578 connect_eigenvalues_slot(
579 const std::function<void(const std::vector<std::complex<double>> &)> &slot,
580 const bool every_iteration = false);
581
589 boost::signals2::connection
590 connect_hessenberg_slot(
591 const std::function<void(const FullMatrix<double> &)> &slot,
592 const bool every_iteration = true);
593
600 boost::signals2::connection
601 connect_krylov_space_slot(
602 const std::function<
603 void(const internal::SolverGMRESImplementation::TmpVectors<VectorType> &)>
604 &slot);
605
606
611 boost::signals2::connection
612 connect_re_orthogonalization_slot(const std::function<void(int)> &slot);
613
614
615 DeclException1(ExcTooFewTmpVectors,
616 int,
617 << "The number of temporary vectors you gave (" << arg1
618 << ") is too small. It should be at least 10 for "
619 << "any results, and much more for reasonable ones.");
620
621protected:
625 AdditionalData additional_data;
626
631 boost::signals2::signal<void(double)> condition_number_signal;
632
637 boost::signals2::signal<void(double)> all_condition_numbers_signal;
638
643 boost::signals2::signal<void(const std::vector<std::complex<double>> &)>
644 eigenvalues_signal;
645
650 boost::signals2::signal<void(const std::vector<std::complex<double>> &)>
651 all_eigenvalues_signal;
652
657 boost::signals2::signal<void(const FullMatrix<double> &)> hessenberg_signal;
658
663 boost::signals2::signal<void(const FullMatrix<double> &)>
664 all_hessenberg_signal;
665
670 boost::signals2::signal<void(
671 const internal::SolverGMRESImplementation::TmpVectors<VectorType> &)>
672 krylov_space_signal;
673
678 boost::signals2::signal<void(int)> re_orthogonalize_signal;
679
685 SolverControl &solver_control;
686
690 virtual double
691 criterion();
692
699 static void
700 compute_eigs_and_cond(
701 const FullMatrix<double> &H_orig,
702 const unsigned int n,
703 const boost::signals2::signal<
704 void(const std::vector<std::complex<double>> &)> &eigenvalues_signal,
705 const boost::signals2::signal<void(const FullMatrix<double> &)>
706 &hessenberg_signal,
707 const boost::signals2::signal<void(double)> &cond_signal);
708
713 internal::SolverGMRESImplementation::ArnoldiProcess<
714 typename VectorType::value_type>
715 arnoldi_process;
716};
717
718
782template <typename VectorType = Vector<double>>
783DEAL_II_CXX20_REQUIRES(concepts::is_vector_space_vector<VectorType>)
784class SolverMPGMRES : public SolverBase<VectorType>
785{
786public:
791 {
795 explicit AdditionalData(const unsigned int max_basis_size = 30,
797 orthogonalization_strategy =
799 delayed_classical_gram_schmidt,
800 const bool use_truncated_mpgmres_strategy = true)
801 : max_basis_size(max_basis_size)
802 , orthogonalization_strategy(orthogonalization_strategy)
803 , use_truncated_mpgmres_strategy(use_truncated_mpgmres_strategy)
804 {}
805
809 unsigned int max_basis_size;
810
815
826 };
827
834
841
845 template <typename MatrixType, typename... PreconditionerTypes>
849 void solve(const MatrixType &A,
850 VectorType &x,
851 const VectorType &b,
852 const PreconditionerTypes &...preconditioners);
853
854protected:
862 {
863 fgmres,
864 truncated_mpgmres,
865 full_mpgmres,
866 };
867
871 template <typename MatrixType, typename... PreconditionerTypes>
872 void
873 solve_internal(const MatrixType &A,
874 VectorType &x,
875 const VectorType &b,
876 const IndexingStrategy &indexing_strategy,
877 const PreconditionerTypes &...preconditioners);
878
879private:
884
890 typename VectorType::value_type>
892};
893
894
895
921template <typename VectorType = Vector<double>>
923class SolverFGMRES : public SolverMPGMRES<VectorType>
924{
925public:
930 {
934 explicit AdditionalData( //
935 const unsigned int max_basis_size = 30,
937 orthogonalization_strategy = LinearAlgebra::OrthogonalizationStrategy::
938 delayed_classical_gram_schmidt)
939 : max_basis_size(max_basis_size)
940 , orthogonalization_strategy(orthogonalization_strategy)
941 {}
942
946 unsigned int max_basis_size;
947
952 };
953
954
961
968
972 template <typename MatrixType, typename... PreconditionerTypes>
976 void solve(const MatrixType &A,
977 VectorType &x,
978 const VectorType &b,
979 const PreconditionerTypes &...preconditioners);
980};
981
985/* --------------------- Inline and template functions ------------------- */
986
987#ifndef DOXYGEN
988
989template <typename VectorType>
992 const unsigned int max_basis_size,
993 const bool right_preconditioning,
994 const bool use_default_residual,
995 const bool force_re_orthogonalization,
996 const bool batched_mode,
997 const LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy)
998 : max_n_tmp_vectors(0)
999 , max_basis_size(max_basis_size)
1000 , right_preconditioning(right_preconditioning)
1001 , use_default_residual(use_default_residual)
1002 , force_re_orthogonalization(force_re_orthogonalization)
1003 , batched_mode(batched_mode)
1004 , orthogonalization_strategy(orthogonalization_strategy)
1005{
1006 Assert(max_basis_size >= 1,
1007 ExcMessage("SolverGMRES needs at least one vector in the "
1008 "Arnoldi basis."));
1009}
1010
1011
1012
1013template <typename VectorType>
1017 const AdditionalData &data)
1018 : SolverBase<VectorType>(cn, mem)
1019 , additional_data(data)
1020 , solver_control(cn)
1021{}
1022
1023
1024
1025template <typename VectorType>
1028 const AdditionalData &data)
1029 : SolverBase<VectorType>(cn)
1030 , additional_data(data)
1031 , solver_control(cn)
1032{}
1033
1034
1035
1036namespace internal
1037{
1038 namespace SolverGMRESImplementation
1039 {
1040 template <typename VectorType>
1041 inline TmpVectors<VectorType>::TmpVectors(const unsigned int max_size,
1043 : mem(vmem)
1044 , data(max_size)
1045 {}
1046
1047
1048
1049 template <typename VectorType>
1050 inline VectorType &
1051 TmpVectors<VectorType>::operator[](const unsigned int i) const
1052 {
1053 AssertIndexRange(i, data.size());
1054
1055 Assert(data[i] != nullptr, ExcNotInitialized());
1056 return *data[i];
1057 }
1058
1059
1060
1061 template <typename VectorType>
1062 inline VectorType &
1063 TmpVectors<VectorType>::operator()(const unsigned int i,
1064 const VectorType &temp)
1065 {
1066 AssertIndexRange(i, data.size());
1067 if (data[i] == nullptr)
1068 {
1069 data[i] = std::move(typename VectorMemory<VectorType>::Pointer(mem));
1070 data[i]->reinit(temp, true);
1071 }
1072 return *data[i];
1073 }
1074
1075
1076
1077 template <typename VectorType>
1078 unsigned int
1079 TmpVectors<VectorType>::size() const
1080 {
1081 return (data.size() > 0 ? data.size() - 1 : 0);
1082 }
1083
1084
1085
1086 template <typename VectorType, typename Enable = void>
1087 struct is_dealii_compatible_vector;
1088
1089 template <typename VectorType>
1090 struct is_dealii_compatible_vector<
1091 VectorType,
1092 std::enable_if_t<!internal::is_block_vector<VectorType>>>
1093 {
1094 static constexpr bool value =
1095 std::is_same_v<
1096 VectorType,
1097 LinearAlgebra::distributed::Vector<typename VectorType::value_type,
1099 std::is_same_v<VectorType, Vector<typename VectorType::value_type>>;
1100 };
1101
1102
1103
1104 template <typename VectorType>
1105 struct is_dealii_compatible_vector<
1106 VectorType,
1107 std::enable_if_t<internal::is_block_vector<VectorType>>>
1108 {
1109 static constexpr bool value =
1110 std::is_same_v<
1111 typename VectorType::BlockType,
1112 LinearAlgebra::distributed::Vector<typename VectorType::value_type,
1114 std::is_same_v<VectorType, Vector<typename VectorType::value_type>>;
1115 };
1116
1117
1118
1119 template <typename VectorType>
1120 struct is_dealii_device_vector : std::false_type
1121 {};
1122
1123 template <typename Number>
1124 struct is_dealii_device_vector<
1125 LinearAlgebra::distributed::Vector<Number, MemorySpace::Default>>
1126 : std::true_type
1127 {};
1128
1129 template <typename Number>
1130 struct is_dealii_device_vector<
1131 LinearAlgebra::distributed::BlockVector<Number, MemorySpace::Default>>
1132 : std::true_type
1133 {};
1134
1135
1136
1137 template <typename VectorType>
1138 constexpr bool use_generic_implementation =
1139 !is_dealii_compatible_vector<VectorType>::value &&
1140 !is_dealii_device_vector<VectorType>::value;
1141
1142
1143
1144 template <typename VectorType>
1145 unsigned int
1146 n_blocks(const VectorType &vector)
1147 {
1149 return vector.n_blocks();
1150 else
1151 return 1;
1152 }
1153
1154
1155
1156 template <typename VectorType,
1157 std::enable_if_t<!IsBlockVector<VectorType>::value, VectorType>
1158 * = nullptr>
1159 VectorType &
1160 block(VectorType &vector, const unsigned int b)
1161 {
1162 AssertDimension(b, 0);
1163 return vector;
1164 }
1165
1166
1167
1168 template <typename VectorType,
1169 std::enable_if_t<!IsBlockVector<VectorType>::value, VectorType>
1170 * = nullptr>
1171 const VectorType &
1172 block(const VectorType &vector, const unsigned int b)
1173 {
1174 AssertDimension(b, 0);
1175 return vector;
1176 }
1177
1178
1179
1180 template <typename VectorType,
1181 std::enable_if_t<IsBlockVector<VectorType>::value, VectorType> * =
1182 nullptr>
1183 typename VectorType::BlockType &
1184 block(VectorType &vector, const unsigned int b)
1185 {
1186 return vector.block(b);
1187 }
1188
1189
1190
1191 template <typename VectorType,
1192 std::enable_if_t<IsBlockVector<VectorType>::value, VectorType> * =
1193 nullptr>
1194 const typename VectorType::BlockType &
1195 block(const VectorType &vector, const unsigned int b)
1196 {
1197 return vector.block(b);
1198 }
1199
1200
1201
1202 template <bool delayed_reorthogonalization,
1203 typename VectorType,
1204 std::enable_if_t<use_generic_implementation<VectorType>,
1205 VectorType> * = nullptr>
1206 void
1207 Tvmult_add(const unsigned int n,
1208 const VectorType &vv,
1209 const TmpVectors<VectorType> &orthogonal_vectors,
1210 Vector<double> &h,
1211 OrthogonalizationData<typename VectorType::value_type> &)
1212 {
1213 for (unsigned int i = 0; i < n; ++i)
1214 {
1215 h(i) += vv * orthogonal_vectors[i];
1216 if (delayed_reorthogonalization)
1217 h(n + i) += orthogonal_vectors[i] * orthogonal_vectors[n - 1];
1218 }
1219 if (delayed_reorthogonalization)
1220 h(n + n) += vv * vv;
1221 }
1222
1223
1224
1225 // worker method for deal.II's vector types implemented in the .cc file
1226 template <bool delayed_reorthogonalization,
1227 typename MemorySpace,
1228 typename Number>
1229 void
1230 do_Tvmult_add(const unsigned int n_vectors,
1231 const std::size_t locally_owned_size,
1232 const Number *current_vector,
1233 OrthogonalizationData<Number> &temp_data,
1234 Vector<double> &b);
1235
1236
1237
1238 template <bool delayed_reorthogonalization,
1239 typename VectorType,
1240 std::enable_if_t<!use_generic_implementation<VectorType>,
1241 VectorType> * = nullptr>
1242 void
1243 Tvmult_add(
1244 const unsigned int n,
1245 const VectorType &vv,
1246 const TmpVectors<VectorType> &orthogonal_vectors,
1247 Vector<double> &h,
1248 OrthogonalizationData<typename VectorType::value_type> &temp_data)
1249 {
1250 using MemorySpace =
1251 std::conditional_t<is_dealii_device_vector<VectorType>::value,
1254 for (unsigned int b = 0; b < n_blocks(vv); ++b)
1255 {
1256 temp_data.vector_ptrs.resize(n);
1257 for (unsigned int i = 0; i < n; ++i)
1258 temp_data.vector_ptrs[i] = block(orthogonal_vectors[i], b).begin();
1259
1260 do_Tvmult_add<delayed_reorthogonalization, MemorySpace>(
1261 n,
1262 block(vv, b).end() - block(vv, b).begin(),
1263 block(vv, b).begin(),
1264 temp_data,
1265 h);
1266 }
1267
1268 Utilities::MPI::sum(h, block(vv, 0).get_mpi_communicator(), h);
1269 }
1270
1271
1272
1273 template <bool delayed_reorthogonalization,
1274 typename VectorType,
1275 std::enable_if_t<use_generic_implementation<VectorType>,
1276 VectorType> * = nullptr>
1277 double
1278 subtract_and_norm(const unsigned int n,
1279 const TmpVectors<VectorType> &orthogonal_vectors,
1280 const Vector<double> &h,
1281 VectorType &vv,
1282 OrthogonalizationData<typename VectorType::value_type> &)
1283 {
1284 Assert(n > 0, ExcInternalError());
1285
1286 VectorType &last_vector =
1287 const_cast<VectorType &>(orthogonal_vectors[n - 1]);
1288 for (unsigned int i = 0; i < n - 1; ++i)
1289 {
1290 if (delayed_reorthogonalization && i + 2 < n)
1291 last_vector.add(-h(n + i), orthogonal_vectors[i]);
1292 vv.add(-h(i), orthogonal_vectors[i]);
1293 }
1294
1295 if (delayed_reorthogonalization)
1296 {
1297 if (n > 1)
1298 last_vector.sadd(1. / h(n + n - 1),
1299 -h(n + n - 2) / h(n + n - 1),
1300 orthogonal_vectors[n - 2]);
1301
1302 // h(n + n) = 0 is lucky breakdown
1303 const double scaling_factor_vv = h(n + n) > 0.0 ?
1304 1. / (h(n + n - 1) * h(n + n)) :
1305 1. / (h(n + n - 1) * h(n + n - 1));
1306 vv.sadd(scaling_factor_vv,
1307 -h(n - 1) * scaling_factor_vv,
1308 last_vector);
1309
1310 // the delayed reorthogonalization computes the norm from other
1311 // quantities
1312 return std::numeric_limits<double>::signaling_NaN();
1313 }
1314 else
1315 return std::sqrt(
1316 vv.add_and_dot(-h(n - 1), orthogonal_vectors[n - 1], vv));
1317 }
1318
1319
1320
1321 // worker method for deal.II's host vector types implemented in the .cc
1322 // file
1323 template <bool delayed_reorthogonalization,
1324 typename MemorySpace,
1325 typename Number>
1326 double
1327 do_subtract_and_norm(const unsigned int n_vectors,
1328 const std::size_t locally_owned_size,
1329 OrthogonalizationData<Number> &temp_data,
1330 const Vector<double> &h,
1331 Number *current_vector);
1332
1333
1334
1335 template <bool delayed_reorthogonalization,
1336 typename VectorType,
1337 std::enable_if_t<!use_generic_implementation<VectorType>,
1338 VectorType> * = nullptr>
1339 double
1340 subtract_and_norm(
1341 const unsigned int n,
1342 const TmpVectors<VectorType> &orthogonal_vectors,
1343 const Vector<double> &h,
1344 VectorType &vv,
1345 OrthogonalizationData<typename VectorType::value_type> &temp_data)
1346 {
1347 using MemorySpace =
1348 std::conditional_t<is_dealii_device_vector<VectorType>::value,
1351 double norm_vv_temp = 0.0;
1352
1353 for (unsigned int b = 0; b < n_blocks(vv); ++b)
1354 {
1355 temp_data.vector_ptrs.resize(n);
1356 for (unsigned int i = 0; i < n; ++i)
1357 temp_data.vector_ptrs[i] = block(orthogonal_vectors[i], b).begin();
1358
1359 norm_vv_temp +=
1360 do_subtract_and_norm<delayed_reorthogonalization, MemorySpace>(
1361 n,
1362 block(vv, b).end() - block(vv, b).begin(),
1363 temp_data,
1364 h,
1365 block(vv, b).begin());
1366 }
1367
1368 return std::sqrt(
1369 Utilities::MPI::sum(norm_vv_temp, block(vv, 0).get_mpi_communicator()));
1370 }
1371
1372
1373
1374 template <typename VectorType,
1375 std::enable_if_t<use_generic_implementation<VectorType>,
1376 VectorType> * = nullptr>
1377 void
1378 add(VectorType &p,
1379 const unsigned int n,
1380 const Vector<double> &h,
1381 const TmpVectors<VectorType> &tmp_vectors,
1382 const bool zero_out,
1383 OrthogonalizationData<typename VectorType::value_type> &)
1384 {
1385 if (zero_out)
1386 p.equ(h(0), tmp_vectors[0]);
1387 else
1388 p.add(h(0), tmp_vectors[0]);
1389
1390 for (unsigned int i = 1; i < n; ++i)
1391 p.add(h(i), tmp_vectors[i]);
1392 }
1393
1394
1395
1396 // worker method for deal.II's host vector types implemented in the .cc
1397 // file
1398 template <typename MemorySpace, typename Number>
1399 void
1400 do_add(const unsigned int n_vectors,
1401 const std::size_t locally_owned_size,
1402 OrthogonalizationData<Number> &temp_data,
1403 const Vector<double> &h,
1404 const bool zero_out,
1405 Number *output);
1406
1407
1408
1409 template <typename VectorType,
1410 std::enable_if_t<!use_generic_implementation<VectorType>,
1411 VectorType> * = nullptr>
1412 void
1413 add(VectorType &p,
1414 const unsigned int n,
1415 const Vector<double> &h,
1416 const TmpVectors<VectorType> &tmp_vectors,
1417 const bool zero_out,
1418 OrthogonalizationData<typename VectorType::value_type> &temp_data)
1419 {
1420 using MemorySpace =
1421 std::conditional_t<is_dealii_device_vector<VectorType>::value,
1424 for (unsigned int b = 0; b < n_blocks(p); ++b)
1425 {
1426 temp_data.vector_ptrs.resize(n);
1427 for (unsigned int i = 0; i < n; ++i)
1428 temp_data.vector_ptrs[i] = block(tmp_vectors[i], b).begin();
1429 do_add<MemorySpace>(n,
1430 block(p, b).end() - block(p, b).begin(),
1431 temp_data,
1432 h,
1433 zero_out,
1434 block(p, b).begin());
1435 }
1436 }
1437
1438
1439
1440 template <typename Number>
1441 inline void
1442 ArnoldiProcess<Number>::initialize(
1443 const LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy,
1444 const unsigned int basis_size,
1445 const bool force_reorthogonalization)
1446 {
1447 this->orthogonalization_strategy = orthogonalization_strategy;
1448 this->do_reorthogonalization = force_reorthogonalization;
1449
1450 hessenberg_matrix.reinit(basis_size + 1, basis_size);
1451 triangular_matrix.reinit(basis_size + 1, basis_size, true);
1452
1453 // some additional vectors, also used in the orthogonalization
1454 projected_rhs.reinit(basis_size + 1, true);
1455 givens_rotations.reserve(basis_size);
1456
1457 if (orthogonalization_strategy ==
1460 h.reinit(2 * basis_size + 3);
1461 else
1462 h.reinit(basis_size + 1);
1463 }
1464
1465
1466
1467 template <typename Number>
1468 template <typename VectorType>
1469 inline double
1470 ArnoldiProcess<Number>::orthonormalize_nth_vector(
1471 const unsigned int n,
1472 TmpVectors<VectorType> &orthogonal_vectors,
1473 const unsigned int accumulated_iterations,
1474 const boost::signals2::signal<void(int)> &reorthogonalize_signal)
1475 {
1476 AssertIndexRange(n, hessenberg_matrix.m());
1477 AssertIndexRange(n, orthogonal_vectors.size() + 1);
1478
1479 VectorType &vv = orthogonal_vectors[n];
1480
1481 double residual_estimate = std::numeric_limits<double>::signaling_NaN();
1482 if (n == 0)
1483 {
1484 givens_rotations.clear();
1485 residual_estimate = vv.l2_norm();
1486 if (residual_estimate != 0.)
1487 vv /= residual_estimate;
1488 projected_rhs(0) = residual_estimate;
1489 }
1490 else if (orthogonalization_strategy ==
1493 {
1494 // The algorithm implemented in the following few lines is algorithm
1495 // 4 of Bielich et al. (2022).
1496
1497 // To avoid un-scaled numbers as appearing with the original
1498 // algorithm by Bielich et al., we use a preliminary scaling of the
1499 // last vector. This will be corrected in the delayed step.
1500 const double previous_scaling = n > 0 ? h(n + n - 2) : 1.;
1501
1502 // Reset h to zero
1503 h.reinit(n + n + 1);
1504
1505 // global reduction
1506 Tvmult_add<true>(n, vv, orthogonal_vectors, h, temp_data);
1507
1508 // delayed correction terms
1509 double tmp = 0;
1510 for (unsigned int i = 0; i < n - 1; ++i)
1511 tmp += h(n + i) * h(n + i);
1512
1513 // catch the case of lucky breakdown (= convergence), when h(n + n -
1514 // 1) = 0 and the algorithm terminates as the h entry will control
1515 // the residual, but we must avoid dividing by zero
1516 const double alpha_j =
1517 h(n + n - 1) == 0. ?
1518 1. :
1519 (h(n + n - 1) > tmp ? std::sqrt(h(n + n - 1) - tmp) :
1520 std::sqrt(h(n + n - 1)));
1521 h(n + n - 1) = alpha_j;
1522
1523 tmp = 0;
1524 for (unsigned int i = 0; i < n - 1; ++i)
1525 tmp += h(i) * h(n + i);
1526 h(n - 1) = (h(n - 1) - tmp) / alpha_j;
1527
1528 // representation of H(j-1)
1529 if (n > 1)
1530 {
1531 for (unsigned int i = 0; i < n - 1; ++i)
1532 hessenberg_matrix(i, n - 2) += h(n + i) * previous_scaling;
1533 hessenberg_matrix(n - 1, n - 2) = alpha_j * previous_scaling;
1534 }
1535 for (unsigned int i = 0; i < n; ++i)
1536 {
1537 double sum = 0;
1538 for (unsigned int j = (i == 0 ? 0 : i - 1); j < n - 1; ++j)
1539 sum += hessenberg_matrix(i, j) * h(n + j);
1540 hessenberg_matrix(i, n - 1) = (h(i) - sum) / alpha_j;
1541 }
1542
1543 // compute norm estimate for approximate convergence criterion
1544 // (value of norm to be corrected in next iteration)
1545 double sum = 0;
1546 for (unsigned int i = 0; i < n - 1; ++i)
1547 sum += h(i) * h(i);
1548 sum += (2. - 1.) * h(n - 1) * h(n - 1);
1549 hessenberg_matrix(n, n - 1) =
1550 std::sqrt(std::abs(h(n + n) - sum)) / alpha_j;
1551
1552 // projection and delayed reorthogonalization. We scale the vector
1553 // vv here by the preliminary norm to avoid working with too large
1554 // values and correct the actual norm in the Hessenberg matrix in
1555 // high precision in the next iteration.
1556 h(n + n) = hessenberg_matrix(n, n - 1);
1557 subtract_and_norm<true>(n, orthogonal_vectors, h, vv, temp_data);
1558
1559 // transform new column of upper Hessenberg matrix into upper
1560 // triangular form by computing the respective factor
1561 residual_estimate = do_givens_rotation(
1562 true, n - 2, triangular_matrix, givens_rotations, projected_rhs);
1563 }
1564 else
1565 {
1566 // need initial norm for detection of re-orthogonalization, see below
1567 double norm_vv = 0.0;
1568 double norm_vv_start = 0;
1569 const bool consider_reorthogonalize =
1570 (do_reorthogonalization == false) && (n % 5 == 0);
1571 if (consider_reorthogonalize)
1572 norm_vv_start = vv.l2_norm();
1573
1574 // Reset h to zero
1575 h.reinit(n);
1576
1577 // run two loops with index 0: orthogonalize, 1: reorthogonalize
1578 for (unsigned int c = 0; c < 2; ++c)
1579 {
1580 // Orthogonalization
1581 if (orthogonalization_strategy ==
1584 {
1585 double htmp = vv * orthogonal_vectors[0];
1586 h(0) += htmp;
1587 for (unsigned int i = 1; i < n; ++i)
1588 {
1589 htmp = vv.add_and_dot(-htmp,
1590 orthogonal_vectors[i - 1],
1591 orthogonal_vectors[i]);
1592 h(i) += htmp;
1593 }
1594
1595 norm_vv = std::sqrt(
1596 vv.add_and_dot(-htmp, orthogonal_vectors[n - 1], vv));
1597 }
1598 else if (orthogonalization_strategy ==
1601 {
1602 Tvmult_add<false>(n, vv, orthogonal_vectors, h, temp_data);
1603 norm_vv = subtract_and_norm<false>(
1604 n, orthogonal_vectors, h, vv, temp_data);
1605 }
1606 else
1607 {
1609 }
1610
1611 if (c == 1)
1612 break; // reorthogonalization already performed -> finished
1613
1614 // Re-orthogonalization if loss of orthogonality detected. For the
1615 // test, use a strategy discussed in C. T. Kelley, Iterative
1616 // Methods for Linear and Nonlinear Equations, SIAM, Philadelphia,
1617 // 1995: Compare the norm of vv after orthogonalization with its
1618 // norm when starting the orthogonalization. If vv became very
1619 // small (here: less than the square root of the machine precision
1620 // times 10), it is almost in the span of the previous vectors,
1621 // which indicates loss of precision.
1622 if (consider_reorthogonalize)
1623 {
1624 if (norm_vv >
1625 10. * norm_vv_start *
1626 std::sqrt(std::numeric_limits<
1627 typename VectorType::value_type>::epsilon()))
1628 break;
1629
1630 else
1631 {
1632 do_reorthogonalization = true;
1633 if (!reorthogonalize_signal.empty())
1634 reorthogonalize_signal(accumulated_iterations);
1635 }
1636 }
1637
1638 if (do_reorthogonalization == false)
1639 break; // no reorthogonalization needed -> finished
1640 }
1641
1642 for (unsigned int i = 0; i < n; ++i)
1643 hessenberg_matrix(i, n - 1) = h(i);
1644 hessenberg_matrix(n, n - 1) = norm_vv;
1645
1646 // norm_vv is a lucky breakdown, the solver will reach convergence,
1647 // but we must not divide by zero here.
1648 if (norm_vv != 0)
1649 vv /= norm_vv;
1650
1651 residual_estimate = do_givens_rotation(
1652 false, n - 1, triangular_matrix, givens_rotations, projected_rhs);
1653 }
1654
1655 return residual_estimate;
1656 }
1657
1658
1659
1660 template <typename Number>
1661 inline double
1662 ArnoldiProcess<Number>::do_givens_rotation(
1663 const bool delayed_reorthogonalization,
1664 const int col,
1665 FullMatrix<double> &matrix,
1666 std::vector<std::pair<double, double>> &rotations,
1667 Vector<double> &rhs)
1668 {
1669 // for the delayed orthogonalization, we can only compute the column of
1670 // the previous iteration (as there will be correction terms added to the
1671 // present column for stability reasons), but we still want to compute
1672 // the residual estimate from the accumulated work; we therefore perform
1673 // givens rotations on two columns simultaneously
1674 if (delayed_reorthogonalization)
1675 {
1676 if (col >= 0)
1677 {
1678 AssertDimension(rotations.size(), static_cast<std::size_t>(col));
1679 matrix(0, col) = hessenberg_matrix(0, col);
1680 }
1681 double H_next = hessenberg_matrix(0, col + 1);
1682 for (int i = 0; i < col; ++i)
1683 {
1684 const double c = rotations[i].first;
1685 const double s = rotations[i].second;
1686 const double Hi = matrix(i, col);
1687 const double Hi1 = hessenberg_matrix(i + 1, col);
1688 H_next = -s * H_next + c * hessenberg_matrix(i + 1, col + 1);
1689 matrix(i, col) = c * Hi + s * Hi1;
1690 matrix(i + 1, col) = -s * Hi + c * Hi1;
1691 }
1692
1693 if (col >= 0)
1694 {
1695 const double H_col1 = hessenberg_matrix(col + 1, col);
1696 const double H_col = matrix(col, col);
1697 const double r = 1. / std::sqrt(H_col * H_col + H_col1 * H_col1);
1698 rotations.emplace_back(H_col * r, H_col1 * r);
1699 matrix(col, col) =
1700 rotations[col].first * H_col + rotations[col].second * H_col1;
1701
1702 rhs(col + 1) = -rotations[col].second * rhs(col);
1703 rhs(col) *= rotations[col].first;
1704
1705 H_next =
1706 -rotations[col].second * H_next +
1707 rotations[col].first * hessenberg_matrix(col + 1, col + 1);
1708 }
1709
1710 const double H_last = hessenberg_matrix(col + 2, col + 1);
1711
1712 // Catch the lucky breakdown case when both the current residual and
1713 // the previous one (after applying the delayed correction from
1714 // re-orthogonalization) are exactly zero. We will finish after this
1715 // step, but must not divide by zero.
1716 if (H_next == 0. && H_last == 0.)
1717 return 0;
1718 else
1719 {
1720 const double r =
1721 1. / std::sqrt(H_next * H_next + H_last * H_last);
1722 return std::abs(H_last * r * rhs(col + 1));
1723 }
1724 }
1725 else
1726 {
1727 AssertDimension(rotations.size(), static_cast<std::size_t>(col));
1728
1729 matrix(0, col) = hessenberg_matrix(0, col);
1730 for (int i = 0; i < col; ++i)
1731 {
1732 const double c = rotations[i].first;
1733 const double s = rotations[i].second;
1734 const double Hi = matrix(i, col);
1735 const double Hi1 = hessenberg_matrix(i + 1, col);
1736 matrix(i, col) = c * Hi + s * Hi1;
1737 matrix(i + 1, col) = -s * Hi + c * Hi1;
1738 }
1739
1740 const double Hi = matrix(col, col);
1741 const double Hi1 = hessenberg_matrix(col + 1, col);
1742
1743 // Catch (rare) lucky breakdown where the previous iteration would
1744 // have been ready but the delayed orthogonalization has prevented
1745 // us from seeing it at that stage, so we must enter also this path
1746 // besides the one a few lines above.
1747 if (Hi == 0. && Hi1 == 0.)
1748 {
1749 rotations.emplace_back(1, 0);
1750 matrix(col, col) = 1;
1751 }
1752 else
1753 {
1754 const double r = (Hi * Hi + Hi1 * Hi1 == 0 ?
1755 1 :
1756 1. / std::sqrt(Hi * Hi + Hi1 * Hi1));
1757 rotations.emplace_back(Hi * r, Hi1 * r);
1758 matrix(col, col) =
1759 rotations[col].first * Hi + rotations[col].second * Hi1;
1760 }
1761
1762 rhs(col + 1) = -rotations[col].second * rhs(col);
1763 rhs(col) *= rotations[col].first;
1764
1765 return std::abs(rhs(col + 1));
1766 }
1767 }
1768
1769
1770
1771 template <typename Number>
1772 inline const Vector<double> &
1773 ArnoldiProcess<Number>::solve_projected_system(
1774 const bool orthogonalization_finished)
1775 {
1776 FullMatrix<double> tmp_triangular_matrix;
1777 Vector<double> tmp_rhs;
1778 FullMatrix<double> *matrix = &triangular_matrix;
1779 Vector<double> *rhs = &projected_rhs;
1780 unsigned int n = givens_rotations.size();
1781
1782 // If we solve with the delayed orthogonalization, we still need to
1783 // perform the elimination of the last column before we can solve the
1784 // projected system. We distinguish two cases, one where the
1785 // orthogonalization has finished (i.e., end of inner iteration in
1786 // GMRES) and we can safely overwrite the content of the tridiagonal
1787 // matrix and right hand side, and the case during the inner iterations,
1788 // where we need to create copies of the matrices in the QR
1789 // decomposition as well as the right hand side.
1790 if (orthogonalization_strategy ==
1793 {
1794 n += 1;
1795 if (!orthogonalization_finished)
1796 {
1797 tmp_triangular_matrix = triangular_matrix;
1798 tmp_rhs = projected_rhs;
1799 std::vector<std::pair<double, double>> tmp_givens_rotations(
1800 givens_rotations);
1801 do_givens_rotation(false,
1802 givens_rotations.size(),
1803 tmp_triangular_matrix,
1804 tmp_givens_rotations,
1805 tmp_rhs);
1806 matrix = &tmp_triangular_matrix;
1807 rhs = &tmp_rhs;
1808 }
1809 else
1810 do_givens_rotation(false,
1811 givens_rotations.size(),
1812 triangular_matrix,
1813 givens_rotations,
1814 projected_rhs);
1815 }
1816
1817 // Now solve the triangular system by backward substitution
1818 projected_solution.reinit(n);
1819 for (int i = n - 1; i >= 0; --i)
1820 {
1821 double s = (*rhs)(i);
1822 for (unsigned int j = i + 1; j < n; ++j)
1823 s -= projected_solution(j) * (*matrix)(i, j);
1824
1825 projected_solution(i) = s / (*matrix)(i, i);
1826 AssertIsFinite(projected_solution(i));
1827 }
1828
1829 return projected_solution;
1830 }
1831
1832
1833
1834 template <typename Number>
1835 inline const FullMatrix<double> &
1836 ArnoldiProcess<Number>::get_hessenberg_matrix() const
1837 {
1838 return hessenberg_matrix;
1839 }
1840
1841
1842
1843 // A comparator for better printing eigenvalues
1844 inline bool
1845 complex_less_pred(const std::complex<double> &x,
1846 const std::complex<double> &y)
1847 {
1848 return x.real() < y.real() ||
1849 (x.real() == y.real() && x.imag() < y.imag());
1850 }
1851 } // namespace SolverGMRESImplementation
1852} // namespace internal
1853
1854
1855
1856template <typename VectorType>
1859 const FullMatrix<double> &H_orig,
1860 const unsigned int n,
1861 const boost::signals2::signal<void(const std::vector<std::complex<double>> &)>
1862 &eigenvalues_signal,
1863 const boost::signals2::signal<void(const FullMatrix<double> &)>
1864 &hessenberg_signal,
1865 const boost::signals2::signal<void(double)> &cond_signal)
1866{
1867 // Avoid copying the Hessenberg matrix if it isn't needed.
1868 if ((!eigenvalues_signal.empty() || !hessenberg_signal.empty() ||
1869 !cond_signal.empty()) &&
1870 n > 0)
1871 {
1872 LAPACKFullMatrix<double> mat(n, n);
1873 for (unsigned int i = 0; i < n; ++i)
1874 for (unsigned int j = 0; j < n; ++j)
1875 mat(i, j) = H_orig(i, j);
1876 hessenberg_signal(H_orig);
1877 // Avoid computing eigenvalues if they are not needed.
1878 if (!eigenvalues_signal.empty())
1879 {
1880 // Copy mat so that we can compute svd below. Necessary since
1881 // compute_eigenvalues will leave mat in state
1882 // LAPACKSupport::unusable.
1883 LAPACKFullMatrix<double> mat_eig(mat);
1884 mat_eig.compute_eigenvalues();
1885 std::vector<std::complex<double>> eigenvalues(n);
1886 for (unsigned int i = 0; i < mat_eig.n(); ++i)
1887 eigenvalues[i] = mat_eig.eigenvalue(i);
1888 // Sort eigenvalues for nicer output.
1889 std::sort(eigenvalues.begin(),
1890 eigenvalues.end(),
1891 internal::SolverGMRESImplementation::complex_less_pred);
1892 eigenvalues_signal(eigenvalues);
1893 }
1894 // Calculate condition number, avoid calculating the svd if a slot
1895 // isn't connected. Need at least a 2-by-2 matrix to do the estimate.
1896 if (!cond_signal.empty() && (mat.n() > 1))
1897 {
1898 mat.compute_svd();
1899 double condition_number =
1900 mat.singular_value(0) / mat.singular_value(mat.n() - 1);
1901 cond_signal(condition_number);
1902 }
1903 }
1904}
1905
1906
1907
1908template <typename VectorType>
1910template <typename MatrixType, typename PreconditionerType>
1914void SolverGMRES<VectorType>::solve(const MatrixType &A,
1915 VectorType &x,
1916 const VectorType &b,
1917 const PreconditionerType &preconditioner)
1918{
1919 std::unique_ptr<LogStream::Prefix> prefix;
1920 if (!additional_data.batched_mode)
1921 prefix = std::make_unique<LogStream::Prefix>("GMRES");
1922
1923 // extra call to std::max to placate static analyzers: coverity rightfully
1924 // complains that data.max_n_tmp_vectors - 2 may overflow
1925 const unsigned int basis_size =
1926 (additional_data.max_basis_size > 0 ?
1927 additional_data.max_basis_size :
1928 std::max(additional_data.max_n_tmp_vectors, 3u) - 2);
1929
1930 // Generate an object where basis vectors are stored.
1932 basis_size + 2, this->memory);
1933
1934 // number of the present iteration; this number is not reset to zero upon a
1935 // restart
1936 unsigned int accumulated_iterations = 0;
1937
1938 const bool do_eigenvalues =
1939 !additional_data.batched_mode &&
1940 (!condition_number_signal.empty() ||
1941 !all_condition_numbers_signal.empty() || !eigenvalues_signal.empty() ||
1942 !all_eigenvalues_signal.empty() || !hessenberg_signal.empty() ||
1943 !all_hessenberg_signal.empty());
1944
1946 double res = std::numeric_limits<double>::lowest();
1947
1948 // switch to determine whether we want a left or a right preconditioner. at
1949 // present, left is default, but both ways are implemented
1950 const bool left_precondition = !additional_data.right_preconditioning;
1951
1952 // Per default the left preconditioned GMRES uses the preconditioned
1953 // residual and the right preconditioned GMRES uses the unpreconditioned
1954 // residual as stopping criterion.
1955 const bool use_default_residual = additional_data.use_default_residual;
1956
1957 // define an alias
1958 VectorType &p = basis_vectors(basis_size + 1, x);
1959
1960 // Following vectors are needed when we are not using the default residuals
1961 // as stopping criterion
1964 if (!use_default_residual)
1965 {
1966 r = std::move(typename VectorMemory<VectorType>::Pointer(this->memory));
1967 x_ = std::move(typename VectorMemory<VectorType>::Pointer(this->memory));
1968 r->reinit(x);
1969 x_->reinit(x);
1970 }
1971
1972 arnoldi_process.initialize(additional_data.orthogonalization_strategy,
1973 basis_size,
1974 additional_data.force_re_orthogonalization);
1975
1977 // outer iteration: loop until we either reach convergence or the maximum
1978 // number of iterations is exceeded. each cycle of this loop amounts to one
1979 // restart
1980 do
1981 {
1982 VectorType &v = basis_vectors(0, x);
1983
1984 // Compute the preconditioned/unpreconditioned residual for left/right
1985 // preconditioning. If 'x' is the zero vector, then we can bypass the
1986 // full computation. But 'x' is only likely to be the zero vector if
1987 // that's what the user provided as the starting guess, so it's only
1988 // worth checking for this in the first iteration. (Calling all_zero()
1989 // costs as much in memory transfer and communication as computing the
1990 // norm of a vector.)
1991 if (left_precondition)
1992 {
1993 if (accumulated_iterations == 0 && x.all_zero())
1994 preconditioner.vmult(v, b);
1995 else
1996 {
1997 A.vmult(p, x);
1998 p.sadd(-1., 1., b);
1999 preconditioner.vmult(v, p);
2000 }
2001 }
2002 else
2003 {
2004 if (accumulated_iterations == 0 && x.all_zero())
2005 v = b;
2006 else
2007 {
2008 A.vmult(v, x);
2009 v.sadd(-1., 1., b);
2010 }
2011 }
2012
2013 const double norm_v = arnoldi_process.orthonormalize_nth_vector(
2014 0, basis_vectors, accumulated_iterations, re_orthogonalize_signal);
2015
2016 // check the residual here as well since it may be that we got the exact
2017 // (or an almost exact) solution vector at the outset. if we wouldn't
2018 // check here, the next scaling operation would produce garbage
2019 if (use_default_residual)
2020 {
2021 res = norm_v;
2022 if (additional_data.batched_mode)
2023 iteration_state = solver_control.check(accumulated_iterations, res);
2024 else
2025 iteration_state =
2026 this->iteration_status(accumulated_iterations, res, x);
2027
2028 if (iteration_state != SolverControl::iterate)
2029 break;
2030 }
2031 else
2032 {
2033 deallog << "default_res=" << norm_v << std::endl;
2034
2035 if (left_precondition)
2036 {
2037 A.vmult(*r, x);
2038 r->sadd(-1., 1., b);
2039 }
2040 else
2041 preconditioner.vmult(*r, v);
2042
2043 res = r->l2_norm();
2044 if (additional_data.batched_mode)
2045 iteration_state = solver_control.check(accumulated_iterations, res);
2046 else
2047 iteration_state =
2048 this->iteration_status(accumulated_iterations, res, x);
2049
2050 if (iteration_state != SolverControl::iterate)
2051 break;
2052 }
2053
2054 // inner iteration doing at most as many steps as the size of the
2055 // Arnoldi basis
2056 unsigned int inner_iteration = 0;
2057 for (; (inner_iteration < basis_size &&
2058 iteration_state == SolverControl::iterate);
2059 ++inner_iteration)
2060 {
2061 ++accumulated_iterations;
2062 // yet another alias
2063 VectorType &vv = basis_vectors(inner_iteration + 1, x);
2064
2065 if (left_precondition)
2066 {
2067 A.vmult(p, basis_vectors[inner_iteration]);
2068 preconditioner.vmult(vv, p);
2069 }
2070 else
2071 {
2072 preconditioner.vmult(p, basis_vectors[inner_iteration]);
2073 A.vmult(vv, p);
2074 }
2075
2076 res =
2077 arnoldi_process.orthonormalize_nth_vector(inner_iteration + 1,
2078 basis_vectors,
2079 accumulated_iterations,
2080 re_orthogonalize_signal);
2081
2082 if (use_default_residual)
2083 {
2084 if (additional_data.batched_mode)
2085 iteration_state =
2086 solver_control.check(accumulated_iterations, res);
2087 else
2088 iteration_state =
2089 this->iteration_status(accumulated_iterations, res, x);
2090 }
2091 else
2092 {
2093 if (!additional_data.batched_mode)
2094 deallog << "default_res=" << res << std::endl;
2095
2096 *x_ = x;
2097 const Vector<double> &projected_solution =
2098 arnoldi_process.solve_projected_system(false);
2099
2100 if (left_precondition)
2101 for (unsigned int i = 0; i < inner_iteration + 1; ++i)
2102 x_->add(projected_solution(i), basis_vectors[i]);
2103 else
2104 {
2105 p = 0.;
2106 for (unsigned int i = 0; i < inner_iteration + 1; ++i)
2107 p.add(projected_solution(i), basis_vectors[i]);
2108 preconditioner.vmult(*r, p);
2109 x_->add(1., *r);
2110 };
2111 A.vmult(*r, *x_);
2112 r->sadd(-1., 1., b);
2113
2114 // Now *r contains the unpreconditioned residual!!
2115 if (left_precondition)
2116 {
2117 res = r->l2_norm();
2118 iteration_state =
2119 this->iteration_status(accumulated_iterations, res, x);
2120 }
2121 else
2122 {
2123 preconditioner.vmult(*x_, *r);
2124 res = x_->l2_norm();
2125
2126 if (additional_data.batched_mode)
2127 iteration_state =
2128 solver_control.check(accumulated_iterations, res);
2129 else
2130 iteration_state =
2131 this->iteration_status(accumulated_iterations, res, x);
2132 }
2133 }
2134 }
2135
2136 // end of inner iteration; now update the global solution vector x with
2137 // the solution of the projected system (least-squares solution)
2138 const Vector<double> &projected_solution =
2139 arnoldi_process.solve_projected_system(true);
2140
2141 if (do_eigenvalues)
2142 compute_eigs_and_cond(arnoldi_process.get_hessenberg_matrix(),
2143 inner_iteration,
2144 all_eigenvalues_signal,
2145 all_hessenberg_signal,
2146 condition_number_signal);
2147
2148 if (left_precondition)
2149 ::internal::SolverGMRESImplementation::add(
2150 x,
2151 inner_iteration,
2152 projected_solution,
2153 basis_vectors,
2154 false,
2155 arnoldi_process.temp_data);
2156 else
2157 {
2158 ::internal::SolverGMRESImplementation::add(
2159 p,
2160 inner_iteration,
2161 projected_solution,
2162 basis_vectors,
2163 true,
2164 arnoldi_process.temp_data);
2165 preconditioner.vmult(v, p);
2166 x.add(1., v);
2167 }
2168
2169 // in the last round, print the eigenvalues from the last Arnoldi step
2170 if (iteration_state != SolverControl::iterate)
2171 {
2172 if (do_eigenvalues)
2173 compute_eigs_and_cond(arnoldi_process.get_hessenberg_matrix(),
2174 inner_iteration,
2175 eigenvalues_signal,
2176 hessenberg_signal,
2177 condition_number_signal);
2178
2179 if (!additional_data.batched_mode && !krylov_space_signal.empty())
2180 krylov_space_signal(basis_vectors);
2181
2182 // end of outer iteration. restart if no convergence and the number of
2183 // iterations is not exceeded
2184 }
2185 }
2186 while (iteration_state == SolverControl::iterate);
2187
2188 // in case of failure: throw exception
2189 AssertThrow(iteration_state == SolverControl::success,
2190 SolverControl::NoConvergence(accumulated_iterations, res));
2191}
2192
2193
2194
2195template <typename VectorType>
2197boost::signals2::connection
2199 const std::function<void(double)> &slot,
2200 const bool every_iteration)
2201{
2202 if (every_iteration)
2203 {
2204 return all_condition_numbers_signal.connect(slot);
2205 }
2206 else
2207 {
2208 return condition_number_signal.connect(slot);
2209 }
2210}
2211
2212
2213
2214template <typename VectorType>
2216boost::signals2::connection SolverGMRES<VectorType>::connect_eigenvalues_slot(
2217 const std::function<void(const std::vector<std::complex<double>> &)> &slot,
2218 const bool every_iteration)
2219{
2220 if (every_iteration)
2221 {
2222 return all_eigenvalues_signal.connect(slot);
2223 }
2224 else
2225 {
2226 return eigenvalues_signal.connect(slot);
2227 }
2228}
2229
2230
2231
2232template <typename VectorType>
2234boost::signals2::connection SolverGMRES<VectorType>::connect_hessenberg_slot(
2235 const std::function<void(const FullMatrix<double> &)> &slot,
2236 const bool every_iteration)
2237{
2238 if (every_iteration)
2239 {
2240 return all_hessenberg_signal.connect(slot);
2241 }
2242 else
2243 {
2244 return hessenberg_signal.connect(slot);
2245 }
2246}
2247
2248
2249
2250template <typename VectorType>
2252boost::signals2::connection SolverGMRES<VectorType>::connect_krylov_space_slot(
2253 const std::function<void(
2255{
2256 return krylov_space_signal.connect(slot);
2257}
2258
2259
2260
2261template <typename VectorType>
2263boost::signals2::connection
2265 const std::function<void(int)> &slot)
2266{
2267 return re_orthogonalize_signal.connect(slot);
2268}
2269
2270
2271
2272template <typename VectorType>
2275{
2276 // dummy implementation. this function is not needed for the present
2277 // implementation of gmres
2279 return 0;
2280}
2281
2282
2283
2284//----------------------------------------------------------------------//
2285
2286
2287
2288template <typename VectorType>
2292 const AdditionalData &data)
2293 : SolverBase<VectorType>(cn, mem)
2294 , additional_data(data)
2295{}
2296
2297
2298
2299template <typename VectorType>
2302 const AdditionalData &data)
2303 : SolverBase<VectorType>(cn)
2304 , additional_data(data)
2305{}
2306
2307
2308
2309template <typename VectorType>
2311template <typename MatrixType, typename... PreconditionerTypes>
2315void SolverMPGMRES<VectorType>::solve(
2316 const MatrixType &A,
2317 VectorType &x,
2318 const VectorType &b,
2319 const PreconditionerTypes &...preconditioners)
2320{
2321 LogStream::Prefix prefix("MPGMRES");
2322
2323 if (additional_data.use_truncated_mpgmres_strategy)
2325 A, x, b, IndexingStrategy::truncated_mpgmres, preconditioners...);
2326 else
2328 A, x, b, IndexingStrategy::full_mpgmres, preconditioners...);
2329}
2330
2331
2332
2333template <typename VectorType>
2335template <typename MatrixType, typename... PreconditionerTypes>
2337 const MatrixType &A,
2338 VectorType &x,
2339 const VectorType &b,
2340 const IndexingStrategy &indexing_strategy,
2341 const PreconditionerTypes &...preconditioners)
2342{
2343 constexpr std::size_t n_preconditioners = sizeof...(PreconditionerTypes);
2344
2345 // A lambda for applying the nth preconditioner to a vector src storing
2346 // the result in dst:
2347
2348 const auto apply_nth_preconditioner = [&](unsigned int n,
2349 auto &dst,
2350 const auto &src) {
2351 // We cycle through all preconditioners and call the nth one:
2352 std::size_t i = 0;
2353
2354 [[maybe_unused]] bool preconditioner_called = false;
2355
2356 const auto call_matching_preconditioner = [&](const auto &preconditioner) {
2357 if (i++ == n)
2358 {
2359 Assert(!preconditioner_called, ::ExcInternalError());
2360 preconditioner_called = true;
2361 preconditioner.vmult(dst, src);
2362 }
2363 };
2364
2365 // https://en.cppreference.com/w/cpp/language/fold
2366 (call_matching_preconditioner(preconditioners), ...);
2367 Assert(preconditioner_called, ::ExcInternalError());
2368 };
2369
2370 std::size_t current_index = 0;
2371
2372 // A lambda that cycles through all preconditioners in sequence while
2373 // applying exactly one preconditioner with each function invocation to
2374 // the vector src and storing the result in dst:
2375
2376 const auto preconditioner_vmult = [&](auto &dst, const auto &src) {
2377 // We have no preconditioner that we could apply
2378 if constexpr (n_preconditioners == 0)
2379 dst = src;
2380 else
2381 {
2382 apply_nth_preconditioner(current_index, dst, src);
2383 current_index = (current_index + 1) % n_preconditioners;
2384 }
2385 };
2386
2387 // Return the correct index for constructing the next vector in the
2388 // Krylov space sequence according to the chosen indexing strategy
2389
2390 const auto previous_vector_index =
2391 [indexing_strategy](unsigned int i) -> unsigned int {
2392 // In the special case of no preconditioners we simply fall back to the
2393 // FGMRES indexing strategy.
2394 if constexpr (n_preconditioners == 0)
2395 return i;
2396 else
2397 {
2398 switch (indexing_strategy)
2399 {
2400 case IndexingStrategy::fgmres:
2401 // 0, 1, 2, 3, ...
2402 return i;
2403 case IndexingStrategy::full_mpgmres:
2404 // 0, 0, ..., 1, 1, ..., 2, 2, ..., 3, 3, ...
2405 return i / n_preconditioners;
2406 case IndexingStrategy::truncated_mpgmres:
2407 // 0, 0, ..., 1, 2, 3, ...
2408 return (1 + i >= n_preconditioners) ?
2409 (1 + i - n_preconditioners) :
2410 0;
2411 default:
2413 return 0;
2414 }
2415 }
2416 };
2417
2419
2420 const unsigned int basis_size = additional_data.max_basis_size;
2421
2422 // Generate an object where basis vectors are stored.
2424 basis_size + 1, this->memory);
2426 basis_size, this->memory);
2427
2428 // number of the present iteration; this number is not reset to zero upon a
2429 // restart
2430 unsigned int accumulated_iterations = 0;
2431
2432 // matrix used for the orthogonalization process later
2433 arnoldi_process.initialize(additional_data.orthogonalization_strategy,
2434 basis_size,
2435 false);
2436
2437 // Iteration starts here
2438 double res = std::numeric_limits<double>::lowest();
2439
2440 do
2441 {
2442 // Compute the residual. If 'x' is the zero vector, then we can bypass
2443 // the full computation. But 'x' is only likely to be the zero vector if
2444 // that's what the user provided as the starting guess, so it's only
2445 // worth checking for this in the first iteration. (Calling all_zero()
2446 // costs as much in memory transfer and communication as computing the
2447 // norm of a vector.)
2448 if (accumulated_iterations == 0 && x.all_zero())
2449 v(0, x) = b;
2450 else
2451 {
2452 A.vmult(v(0, x), x);
2453 v[0].sadd(-1., 1., b);
2454 }
2455
2456 res = arnoldi_process.orthonormalize_nth_vector(0, v);
2457 iteration_state = this->iteration_status(accumulated_iterations, res, x);
2458 if (iteration_state == SolverControl::success)
2459 break;
2460
2461 unsigned int inner_iteration = 0;
2462 for (; (inner_iteration < basis_size &&
2463 iteration_state == SolverControl::iterate);
2464 ++inner_iteration)
2465 {
2466 preconditioner_vmult(z(inner_iteration, x),
2467 v[previous_vector_index(inner_iteration)]);
2468 A.vmult(v(inner_iteration + 1, x), z[inner_iteration]);
2469
2470 res =
2471 arnoldi_process.orthonormalize_nth_vector(inner_iteration + 1, v);
2472
2473 // check convergence. note that the vector 'x' we pass to the
2474 // criterion is not the final solution we compute if we
2475 // decide to jump out of the iteration (we update 'x' again
2476 // right after the current loop)
2477 iteration_state =
2478 this->iteration_status(++accumulated_iterations, res, x);
2479 }
2480
2481 // Solve triangular system with projected quantities and update solution
2482 // vector
2483 const Vector<double> &projected_solution =
2484 arnoldi_process.solve_projected_system(true);
2485 ::internal::SolverGMRESImplementation::add(
2486 x,
2487 inner_iteration,
2488 projected_solution,
2489 z,
2490 false,
2491 arnoldi_process.temp_data);
2492 }
2493 while (iteration_state == SolverControl::iterate);
2494
2495 // in case of failure: throw exception
2496 if (iteration_state != SolverControl::success)
2497 AssertThrow(false,
2498 SolverControl::NoConvergence(accumulated_iterations, res));
2499}
2500
2501
2502
2503//----------------------------------------------------------------------//
2504
2505
2506
2507template <typename VectorType>
2511 const AdditionalData &data)
2513 cn,
2514 mem,
2515 typename SolverMPGMRES<VectorType>::AdditionalData{
2516 data.max_basis_size,
2517 data.orthogonalization_strategy,
2518 true})
2519{}
2520
2521
2522
2523template <typename VectorType>
2526 const AdditionalData &data)
2528 cn,
2529 typename SolverMPGMRES<VectorType>::AdditionalData{
2530 data.max_basis_size,
2531 data.orthogonalization_strategy,
2532 true})
2533{}
2534
2535
2536
2537template <typename VectorType>
2539template <typename MatrixType, typename... PreconditionerTypes>
2543void SolverFGMRES<VectorType>::solve(
2544 const MatrixType &A,
2545 VectorType &x,
2546 const VectorType &b,
2547 const PreconditionerTypes &...preconditioners)
2548{
2549 LogStream::Prefix prefix("FGMRES");
2551 A, x, b, SolverFGMRES::IndexingStrategy::fgmres, preconditioners...);
2552}
2553
2554
2555#endif // DOXYGEN
2556
2558
2559#endif
*  iterator end()
*  *  for(const auto &cell :triangulation.active_cell_iterators())
*  *  iterator begin()
virtual State check(const unsigned int step, const double check_value)
@ iterate
Continue iteration.
@ success
Stop iteration, goal reached.
SolverFGMRES(SolverControl &cn, VectorMemory< VectorType > &mem, const AdditionalData &data=AdditionalData())
SolverFGMRES(SolverControl &cn, const AdditionalData &data=AdditionalData())
SolverGMRES(const SolverGMRES< VectorType > &)=delete
boost::signals2::connection connect_condition_number_slot(const std::function< void(double)> &slot, const bool every_iteration=false)
boost::signals2::connection connect_krylov_space_slot(const std::function< void(const internal::SolverGMRESImplementation::TmpVectors< VectorType > &)> &slot)
boost::signals2::connection connect_re_orthogonalization_slot(const std::function< void(int)> &slot)
static void compute_eigs_and_cond(const FullMatrix< double > &H_orig, const unsigned int n, const boost::signals2::signal< void(const std::vector< std::complex< double > > &)> &eigenvalues_signal, const boost::signals2::signal< void(const FullMatrix< double > &)> &hessenberg_signal, const boost::signals2::signal< void(double)> &cond_signal)
SolverGMRES(SolverControl &cn, VectorMemory< VectorType > &mem, const AdditionalData &data=AdditionalData())
boost::signals2::connection connect_hessenberg_slot(const std::function< void(const FullMatrix< double > &)> &slot, const bool every_iteration=true)
SolverGMRES(SolverControl &cn, const AdditionalData &data=AdditionalData())
void solve(const MatrixType &A, VectorType &x, const VectorType &b, const PreconditionerType &preconditioner)
virtual double criterion()
boost::signals2::connection connect_eigenvalues_slot(const std::function< void(const std::vector< std::complex< double > > &)> &slot, const bool every_iteration=false)
SolverMPGMRES(SolverControl &cn, VectorMemory< VectorType > &mem, const AdditionalData &data=AdditionalData())
internal::SolverGMRESImplementation::ArnoldiProcess< typename VectorType::value_type > arnoldi_process
SolverMPGMRES(SolverControl &cn, const AdditionalData &data=AdditionalData())
AdditionalData additional_data
void solve_internal(const MatrixType &A, VectorType &x, const VectorType &b, const IndexingStrategy &indexing_strategy, const PreconditionerTypes &...preconditioners)
virtual size_type size() const override
virtual void reinit(const size_type N, const bool omit_zeroing_entries=false)
const FullMatrix< double > & get_hessenberg_matrix() const
LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy
double orthonormalize_nth_vector(const unsigned int n, TmpVectors< VectorType > &orthogonal_vectors, const unsigned int accumulated_iterations=0, const boost::signals2::signal< void(int)> &reorthogonalize_signal=boost::signals2::signal< void(int)>())
const Vector< double > & solve_projected_system(const bool orthogonalization_finished)
void initialize(const LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy, const unsigned int max_basis_size, const bool force_reorthogonalization)
std::vector< std::pair< double, double > > givens_rotations
double do_givens_rotation(const bool delayed_reorthogonalization, const int col, FullMatrix< double > &matrix, std::vector< std::pair< double, double > > &rotations, Vector< double > &rhs)
std::vector< typename VectorMemory< VectorType >::Pointer > data
TmpVectors(const unsigned int max_size, VectorMemory< VectorType > &vmem)
VectorType & operator[](const unsigned int i) const
VectorType & operator()(const unsigned int i, const VectorType &temp)
#define DEAL_II_NAMESPACE_OPEN
Definition config.h:38
#define DEAL_II_CXX20_REQUIRES(condition)
Definition config.h:249
#define DEAL_II_NAMESPACE_CLOSE
Definition config.h:39
#define DEAL_II_ASSERT_UNREACHABLE()
static ::ExceptionBase & ExcNotImplemented()
#define Assert(cond, exc)
#define AssertIsFinite(number)
#define AssertDimension(dim1, dim2)
#define AssertIndexRange(index, range)
static ::ExceptionBase & ExcInternalError()
static ::ExceptionBase & ExcNotInitialized()
#define DeclException1(Exception1, type1, outsequence)
static ::ExceptionBase & ExcMessage(std::string arg1)
#define AssertThrow(cond, exc)
LogStream deallog
Definition logstream.cc:36
std::vector< index_type > data
Definition mpi.cc:734
types::global_dof_index locally_owned_size
Definition mpi.cc:821
@ matrix
Contents is actually a matrix.
constexpr char A
Tpetra::Vector< Number, LO, GO, NodeType< MemorySpace > > VectorType
Tpetra::CrsMatrix< Number, LO, GO, NodeType< MemorySpace > > MatrixType
std::enable_if_t< IsBlockVector< VectorType >::value, unsigned int > n_blocks(const VectorType &vector)
Definition operators.h:47
SymmetricTensor< 2, dim, Number > b(const Tensor< 2, dim, Number > &F)
*  *  *  RotationFunction< dim, Number >::RotationFunction Number(dim)
T sum(const T &t, const MPI_Comm mpi_communicator)
void do_add(const unsigned int n_vectors, const std::size_t locally_owned_size, OrthogonalizationData< Number > &temp_data, const Vector< double > &h, const bool zero_out, Number *output)
void do_Tvmult_add(const unsigned int n_vectors, const std::size_t locally_owned_size, const Number *current_vector, OrthogonalizationData< Number > &temp_data, Vector< double > &h)
double do_subtract_and_norm(const unsigned int n_vectors, const std::size_t locally_owned_size, OrthogonalizationData< Number > &temp_data, const Vector< double > &h, Number *current_vector)
void reinit(MatrixBlock< MatrixType > &v, const BlockSparsityPattern &p)
STL namespace.
::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > sqrt(const ::VectorizedArray< Number, width > &)
::VectorizedArray< Number, width > abs(const ::VectorizedArray< Number, width > &)
AdditionalData(const unsigned int max_basis_size=30, const LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy=LinearAlgebra::OrthogonalizationStrategy::delayed_classical_gram_schmidt)
LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy
AdditionalData(const unsigned int max_basis_size=30, const bool right_preconditioning=false, const bool use_default_residual=true, const bool force_re_orthogonalization=false, const bool batched_mode=false, const LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy=LinearAlgebra::OrthogonalizationStrategy::delayed_classical_gram_schmidt)
LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy
AdditionalData(const unsigned int max_basis_size=30, const LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy=LinearAlgebra::OrthogonalizationStrategy::delayed_classical_gram_schmidt, const bool use_truncated_mpgmres_strategy=true)
LinearAlgebra::OrthogonalizationStrategy orthogonalization_strategy
std::shared_ptr< DeviceData< Number > > device_data
std::array< Number, 1 > eigenvalues(const SymmetricTensor< 2, 1, Number > &T)