FlexibleSolver_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2019, 2020 SINTEF Digital, Mathematics and Cybernetics.
3 Copyright 2020 Equinor.
4
5 This file is part of the Open Porous Media project (OPM).
6
7 OPM is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 OPM is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with OPM. If not, see <http://www.gnu.org/licenses/>.
19*/
20
21#ifndef OPM_FLEXIBLE_SOLVER_IMPL_HEADER_INCLUDED
22#define OPM_FLEXIBLE_SOLVER_IMPL_HEADER_INCLUDED
23
24#include <opm/common/ErrorMacros.hpp>
25#include <opm/common/TimingMacros.hpp>
37
38#if HAVE_AVX2_EXTENSION
41#endif
42
43#include <dune/common/fmatrix.hh>
44#include <dune/istl/bcrsmatrix.hh>
45#include <dune/istl/multitypeblockvector.hh>
46#include <dune/istl/solvers.hh>
47#include <dune/istl/umfpack.hh>
48#include <dune/istl/owneroverlapcopy.hh>
49#include <dune/istl/paamg/pinfo.hh>
50#include <type_traits>
51
52namespace Opm::detail {
53template <typename T>
54struct is_multi_type_block_vector : std::false_type {};
55template <typename... Args>
56struct is_multi_type_block_vector<Dune::MultiTypeBlockVector<Args...>> : std::true_type {};
57template <typename T>
59} // namespace Opm::detail
61#if HAVE_CUDA
62#if USE_HIP
63#include <opm/simulators/linalg/gpuistl_hip/SolverAdapter.hpp>
64#else
66#endif
67#endif
69namespace Dune
70{
72 template <class Operator>
74 FlexibleSolver(Operator& op,
75 const Opm::PropertyTree& prm,
76 const std::function<VectorType()>& weightsCalculator,
77 std::size_t pressureIndex)
78 {
79 init(op, Dune::Amg::SequentialInformation(), prm, weightsCalculator,
80 pressureIndex);
81 }
82
84 template <class Operator>
85 template <class Comm>
87 FlexibleSolver(Operator& op,
88 const Comm& comm,
89 const Opm::PropertyTree& prm,
90 const std::function<VectorType()>& weightsCalculator,
91 std::size_t pressureIndex)
92 {
93 init(op, comm, prm, weightsCalculator, pressureIndex);
94 }
95
96 template <class Operator>
97 void
100 {
101 if (direct_solver_) {
102 auto* direct_precond = dynamic_cast<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>*>(preconditioner_.get());
103 if (direct_precond && direct_precond->needsRebuild()) {
104 recreateDirectSolver();
105 direct_precond->resetNeedsRebuild();
106 }
107 }
108 linsolver_->apply(x, rhs, res);
109 }
110
111 template <class Operator>
112 void
114 apply(VectorType& x, VectorType& rhs, double reduction, Dune::InverseOperatorResult& res)
115 {
116 if (direct_solver_) {
117 auto* direct_precond = dynamic_cast<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>*>(preconditioner_.get());
118 if (direct_precond && direct_precond->needsRebuild()) {
119 recreateDirectSolver();
120 direct_precond->resetNeedsRebuild();
121 }
122 }
123 linsolver_->apply(x, rhs, reduction, res);
124 }
125
127 template <class Operator>
128 auto
131 {
132 return *preconditioner_;
133 }
134
135 template <class Operator>
136 Dune::SolverCategory::Category
138 category() const
139 {
140 return linearoperator_for_solver_->category();
141 }
142
143 // Machinery for making sequential or parallel operators/preconditioners/scalar products.
144 template <class Operator>
145 template <class Comm>
146 void
148 initOpPrecSp(Operator& op,
149 const Opm::PropertyTree& prm,
150 const std::function<VectorType()> weightsCalculator,
151 const Comm& comm,
152 std::size_t pressureIndex)
153 {
154 // Parallel case.
155 linearoperator_for_solver_ = &op;
156 const std::string solver_type = prm.get<std::string>("solver", "bicgstab");
157 auto child = prm.get_child_optional("preconditioner");
158 if (solver_type == "umfpack") {
159 if (comm.communicator().size() > 1) {
160 OPM_THROW(std::invalid_argument,
161 "UMFPACK is only supported for sequential linear solves. "
162 "Please use an iterative solver for distributed matrices.");
163 }
164 preconditioner_ = std::make_shared<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>>(
165 linearoperator_for_solver_->category());
166 } else {
168 child ? *child : Opm::PropertyTree(),
169 weightsCalculator,
170 comm,
171 pressureIndex);
172 }
173 scalarproduct_ = Dune::createScalarProduct<VectorType, Comm>(comm, op.category());
174 }
175
176 template <class Operator>
177 void
178 FlexibleSolver<Operator>::
179 initOpPrecSp(Operator& op,
180 const Opm::PropertyTree& prm,
181 const std::function<VectorType()> weightsCalculator,
182 const Dune::Amg::SequentialInformation&,
183 std::size_t pressureIndex)
184 {
185 // Sequential case.
186 linearoperator_for_solver_ = &op;
187 const std::string solver_type = prm.get<std::string>("solver", "bicgstab");
188 auto child = prm.get_child_optional("preconditioner");
189 if (solver_type == "umfpack") {
190 preconditioner_ = std::make_shared<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>>(
191 linearoperator_for_solver_->category());
192 } else {
194 child ? *child : Opm::PropertyTree(),
195 weightsCalculator,
196 pressureIndex);
197 }
198 scalarproduct_ = std::make_shared<Dune::SeqScalarProduct<VectorType>>();
199 }
200
201
202 template <class Operator>
203 template <class Comm>
204 void
205 FlexibleSolver<Operator>::
206 initSolver(const Opm::PropertyTree& prm, const Comm& comm)
207 {
208 const bool is_iorank = comm.communicator().rank() == 0;
209 const double tol = prm.get<double>("tol", 1e-2);
210 const int maxiter = prm.get<int>("maxiter", 200);
211 const int verbosity = is_iorank ? prm.get<int>("verbosity", 0) : 0;
212 const std::string solver_type = prm.get<std::string>("solver", "bicgstab");
213
214
215 // make sure it is nullptr at the start (used for error checking in the end).
216 // while the linSolver_ is initalized as a nullptr, we want to make sure it is reset here,
217 // simply because we will check if it is at the end of this function and need to keep this invariant
218 // (that it is nullptr at the start of this function).
219 linsolver_.reset();
220 direct_solver_ = false;
221 if (solver_type == "bicgstab") {
222 linsolver_ = std::make_shared<Dune::BiCGSTABSolver<VectorType>>(*linearoperator_for_solver_,
223 *scalarproduct_,
224 *preconditioner_,
225 tol, // desired residual reduction factor
226 maxiter, // maximum number of iterations
227 verbosity);
228#if HAVE_AVX2_EXTENSION
229 } else if (solver_type == "mixed-legacy") {
230 if constexpr (Opm::is_gpu_operator_v<Operator>) {
231 OPM_THROW(std::invalid_argument, "legacy mixed-bicgstab solver not supported for GPU operators");
232 } else if constexpr (Opm::detail::is_multi_type_block_vector_v<VectorType>) {
233 OPM_THROW(std::invalid_argument, "legacy mixed-bicgstab solver not supported for multi-type block vectors.");
234 } else if constexpr (std::is_same_v<typename VectorType::field_type, float>){
235 OPM_THROW(std::invalid_argument, "legacy mixed-bicgstab solver not supported for single precision.");
236 } else {
237 const std::string prec_type = prm.get<std::string>("preconditioner.type", "error");
238 bool use_mixed_dilu= (prec_type=="legacy-mixed-dilu");
239 using MatrixType = decltype(linearoperator_for_solver_->getmat());
240 linsolver_ = std::make_shared<Dune::MixedSolver<VectorType,MatrixType>>(
241 linearoperator_for_solver_->getmat(),
242 tol,
243 maxiter,
244 use_mixed_dilu
245 );
246 }
247 // MixedBiCGSTABSolver starts here
248 } else if (solver_type == "mixed-bicgstab") {
249 if constexpr (Opm::is_gpu_operator_v<Operator>) {
250 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for GPU operators");
251 } else if constexpr (Opm::detail::is_multi_type_block_vector_v<VectorType>) {
252 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for multi-type block vectors.");
253 } else if constexpr (std::is_same_v<typename VectorType::field_type, float>){
254 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for single precision.");
255 } else {
256 linsolver_ = std::make_shared<Dune::MixedBiCGSTABSolver<Comm,Operator,VectorType>>(linearoperator_for_solver_,
257 scalarproduct_,
258 preconditioner_,
259 tol, // desired residual reduction factor
260 maxiter, // maximum number of iterations
261 verbosity,
262 comm);
263 }
264#endif
265 } else if (solver_type == "cg") {
266 linsolver_ = std::make_shared<Dune::CGSolver<VectorType>>(*linearoperator_for_solver_,
267 *scalarproduct_,
268 *preconditioner_,
269 tol, // desired residual reduction factor
270 maxiter, // maximum number of iterations
271 verbosity);
272 } else if (solver_type == "loopsolver") {
273 linsolver_ = std::make_shared<Dune::LoopSolver<VectorType>>(*linearoperator_for_solver_,
274 *scalarproduct_,
275 *preconditioner_,
276 tol, // desired residual reduction factor
277 maxiter, // maximum number of iterations
278 verbosity);
279 } else if (solver_type == "gmres") {
280 int restart = prm.get<int>("restart", 15);
281 linsolver_ = std::make_shared<Dune::RestartedGMResSolver<VectorType>>(*linearoperator_for_solver_,
282 *scalarproduct_,
283 *preconditioner_,
284 tol,// desired residual reduction factor
285 restart,
286 maxiter, // maximum number of iterations
287 verbosity);
288 } else if (solver_type == "flexgmres") {
289 if constexpr (Opm::is_gpu_operator_v<Operator>) {
290 OPM_THROW(std::invalid_argument, "flexgmres solver not supported for GPU operators.");
291 } else {
292 int restart = prm.get<int>("restart", 15);
293 linsolver_ = std::make_shared<Dune::RestartedFlexibleGMResSolver<VectorType>>(*linearoperator_for_solver_,
294 *scalarproduct_,
295 *preconditioner_,
296 tol,// desired residual reduction factor
297 restart,
298 maxiter, // maximum number of iterations
299 verbosity);
300 }
301 } else if (solver_type == "preconditioner2inverseoperator") {
302 if (!preconditioner_) {
303 OPM_THROW(std::invalid_argument,
304 "Properties: Solver preconditioner2inverseoperator requires a preconditioner.");
305 }
306 linsolver_ = std::make_shared<Dune::Preconditioner2InverseOperator<VectorType>>(preconditioner_);
307 } else {
308 if constexpr (!Opm::is_gpu_operator_v<Operator> && !Opm::detail::is_multi_type_block_vector_v<VectorType>) {
309#if HAVE_SUITESPARSE_UMFPACK
310 if (solver_type == "umfpack") {
311 if constexpr (std::is_same_v<typename VectorType::field_type,float>) {
312 OPM_THROW(std::invalid_argument, "UMFPack cannot be used with floats");
313 } else {
314 using MatrixType = std::remove_const_t<std::remove_reference_t<decltype(linearoperator_for_solver_->getmat())>>;
315 linsolver_ = std::make_shared<Dune::UMFPack<MatrixType>>(linearoperator_for_solver_->getmat(), verbosity, false);
316 direct_solver_ = true;
317 }
318#endif
319#if HAVE_CUDA
320 } else if (solver_type == "gpubicgstab") {
321 if constexpr (VectorType::block_type::dimension
323 linsolver_.reset(new Opm::gpuistl::SolverAdapter<Operator,
324 Dune::BiCGSTABSolver,
325 VectorType>(
326 *linearoperator_for_solver_,
327 *scalarproduct_,
328 preconditioner_,
329 tol, // desired residual reduction factor
330 maxiter, // maximum number of iterations
331 verbosity,
332 comm));
333 }
334#endif
335 }
336 }
337 }
338 if (!linsolver_) {
339 OPM_THROW(std::invalid_argument,
340 "Properties: Solver " + solver_type + " not known.");
341 }
342 }
343
344
345 // For now, the only direct solver we support is UMFPACK from SuiteSparse.
346 // When the matrix is updated (keeping sparsity pattern) it is possible to
347 // exploit separation of symbolic and numeric factorization, but we do not
348 // do so at this point. For complete generality, the solver abstract class
349 // Dune::InverseOperator<> should be extended with an update() function.
350 template <class Operator>
351 void
352 FlexibleSolver<Operator>::
353 recreateDirectSolver()
354 {
355#if HAVE_SUITESPARSE_UMFPACK
356 if constexpr (!Opm::is_gpu_operator_v<Operator> && !Opm::detail::is_multi_type_block_vector_v<VectorType>) {
357 if constexpr (std::is_same_v<typename VectorType::field_type, float>) {
358 OPM_THROW(std::invalid_argument, "UMFPack cannot be used with floats");
359 } else {
360 using MatrixType = std::remove_const_t<std::remove_reference_t<decltype(linearoperator_for_solver_->getmat())>>;
361 linsolver_ = std::make_shared<Dune::UMFPack<MatrixType>>(linearoperator_for_solver_->getmat(), 0, false);
362 }
363 }
364#else
365 OPM_THROW(std::logic_error, "Direct solver specified, but the FlexibleSolver class was not compiled with SuiteSparse support.");
366#endif
367 }
368
369
370 // Main initialization routine.
371 // Call with Comm == Dune::Amg::SequentialInformation to get a serial solver.
372 template <class Operator>
373 template <class Comm>
374 void
376 init(Operator& op,
377 const Comm& comm,
378 const Opm::PropertyTree& prm,
379 const std::function<VectorType()> weightsCalculator,
380 std::size_t pressureIndex)
381 {
382 initOpPrecSp(op, prm, weightsCalculator, comm, pressureIndex);
383 initSolver(prm, comm);
384 }
385
386} // namespace Dune
387
388
389// Macros to simplify explicit instantiation of FlexibleSolver for various block sizes.
390
391// Vectors and matrices.
392template<class Scalar, int N>
394template<class Scalar, int N>
396
397// Sequential operators.
398template<class Scalar, int N>
399using SeqOpM = Dune::MatrixAdapter<OBM<Scalar,N>, BV<Scalar,N>, BV<Scalar,N>>;
400template<class Scalar, int N>
402
403#if HAVE_MPI
404
405// Parallel communicator and operators.
406using Comm = Dune::OwnerOverlapCopyCommunication<int, int>;
407template<class Scalar, int N>
409template<class Scalar, int N>
411template<class Scalar, int N>
412using ParOpD = Dune::OverlappingSchwarzOperator<OBM<Scalar,N>, BV<Scalar,N>, BV<Scalar,N>, Comm>;
413
414// Note: we must instantiate the constructor that is a template.
415// This is only needed in the parallel case, since otherwise the Comm type is
416// not a template argument but always SequentialInformation.
417
418#define INSTANTIATE_FLEXIBLESOLVER_OP(...) \
419 template class Dune::FlexibleSolver<__VA_ARGS__>; \
420 template Dune::FlexibleSolver<__VA_ARGS__>:: \
421 FlexibleSolver(__VA_ARGS__& op, \
422 const Comm& comm, \
423 const Opm::PropertyTree& prm, \
424 const std::function<typename __VA_ARGS__::domain_type()>& weightsCalculator, \
425 std::size_t pressureIndex);
426
427#define INSTANTIATE_FLEXIBLESOLVER(T,N) \
428 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpM<T,N>); \
429 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpW<T,N>); \
430 INSTANTIATE_FLEXIBLESOLVER_OP(ParOpM<T,N>); \
431 INSTANTIATE_FLEXIBLESOLVER_OP(ParOpW<T,N>); \
432 INSTANTIATE_FLEXIBLESOLVER_OP(ParOpD<T,N>);
433
434#else // HAVE_MPI
435
436#define INSTANTIATE_FLEXIBLESOLVER_OP(...) \
437 template class Dune::FlexibleSolver<__VA_ARGS__>;
438
439#define INSTANTIATE_FLEXIBLESOLVER(T,N) \
440 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpM<T,N>); \
441 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpW<T,N>);
442
443#endif // HAVE_MPI
444
445#endif // OPM_FLEXIBLE_SOLVER_IMPL_HEADER_INCLUDED
Dune::OverlappingSchwarzOperator< OBM< Scalar, N >, BV< Scalar, N >, BV< Scalar, N >, Comm > ParOpD
Definition: FlexibleSolver_impl.hpp:412
Opm::BlockVector< Dune::FieldVector< Scalar, N > > BV
Definition: FlexibleSolver_impl.hpp:393
Dune::OwnerOverlapCopyCommunication< int, int > Comm
Definition: FlexibleSolver_impl.hpp:406
Dune::MatrixAdapter< OBM< Scalar, N >, BV< Scalar, N >, BV< Scalar, N > > SeqOpM
Definition: FlexibleSolver_impl.hpp:399
Opm::BCRSMatrix< Opm::MatrixBlock< Scalar, N, N > > OBM
Definition: FlexibleSolver_impl.hpp:395
Definition: PreconditionerWithUpdate.hpp:98
Definition: FlexibleSolver.hpp:45
Dune::SolverCategory::Category category() const override
Definition: FlexibleSolver_impl.hpp:138
void apply(VectorType &x, VectorType &rhs, Dune::InverseOperatorResult &res) override
Definition: FlexibleSolver_impl.hpp:99
typename Operator::domain_type VectorType
Definition: FlexibleSolver.hpp:47
FlexibleSolver(Operator &op, const Opm::PropertyTree &prm, const std::function< VectorType()> &weightsCalculator, std::size_t pressureIndex)
Create a sequential solver.
Definition: FlexibleSolver_impl.hpp:74
AbstractPrecondType & preconditioner()
Access the contained preconditioner.
Definition: FlexibleSolver_impl.hpp:130
Dune linear operator that assumes ghost rows are ordered after interior rows. Avoids some computation...
Definition: WellOperators.hpp:412
static PrecPtr create(const Operator &op, const PropertyTree &prm, const std::function< Vector()> &weightsCalculator={}, std::size_t pressureIndex=std::numeric_limits< std::size_t >::max())
Definition: PreconditionerFactory_impl.hpp:155
Hierarchical collection of key/value pairs.
Definition: PropertyTree.hpp:39
T get(const std::string &key) const
std::optional< PropertyTree > get_child_optional(const std::string &key) const
Adapter to combine a matrix and another linear operator into a combined linear operator.
Definition: WellOperators.hpp:306
Adapter to combine a matrix and another linear operator into a combined linear operator.
Definition: WellOperators.hpp:229
Wraps a CUDA solver to work with CPU data.
Definition: gpuistl/SolverAdapter.hpp:51
Definition: fvbaseprimaryvariables.hh:161
Definition: flashcompositionstep.hh:36
constexpr bool is_multi_type_block_vector_v
Definition: FlexibleSolver_impl.hpp:58
Dune::InverseOperatorResult InverseOperatorResult
Definition: GpuBridge.hpp:32
Dune::BCRSMatrix< B, A > BCRSMatrix
Definition: BCRSMatrix.hpp:35
constexpr int max_gpu_instantiated_block_size
Definition: is_gpu_operator.hpp:87
Dune::BlockVector< B, A > BlockVector
Definition: BlockVector.hpp:35
Definition: FlexibleSolver_impl.hpp:54