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>
35
36#if HAVE_AVX2_EXTENSION
39#endif
40
41#include <dune/common/fmatrix.hh>
42#include <dune/istl/bcrsmatrix.hh>
43#include <dune/istl/multitypeblockvector.hh>
44#include <dune/istl/solvers.hh>
45#include <dune/istl/umfpack.hh>
46#include <dune/istl/owneroverlapcopy.hh>
47#include <dune/istl/paamg/pinfo.hh>
48#include <type_traits>
49
50namespace Opm::detail {
51template <typename T>
52struct is_multi_type_block_vector : std::false_type {};
53template <typename... Args>
54struct is_multi_type_block_vector<Dune::MultiTypeBlockVector<Args...>> : std::true_type {};
55template <typename T>
57} // namespace Opm::detail
58
59#if HAVE_CUDA
60#if USE_HIP
61#include <opm/simulators/linalg/gpuistl_hip/SolverAdapter.hpp>
62#else
64#endif
65#endif
67namespace Dune
70 template <class Operator>
72 FlexibleSolver(Operator& op,
74 const std::function<VectorType()>& weightsCalculator,
75 std::size_t pressureIndex)
76 {
77 init(op, Dune::Amg::SequentialInformation(), prm, weightsCalculator,
78 pressureIndex);
79 }
80
82 template <class Operator>
83 template <class Comm>
85 FlexibleSolver(Operator& op,
86 const Comm& comm,
87 const Opm::PropertyTree& prm,
88 const std::function<VectorType()>& weightsCalculator,
89 std::size_t pressureIndex)
90 {
91 init(op, comm, prm, weightsCalculator, pressureIndex);
92 }
93
94 template <class Operator>
95 void
98 {
99 if (direct_solver_) {
100 auto* direct_precond = dynamic_cast<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>*>(preconditioner_.get());
101 if (direct_precond && direct_precond->needsRebuild()) {
102 recreateDirectSolver();
103 direct_precond->resetNeedsRebuild();
104 }
105 }
106 linsolver_->apply(x, rhs, res);
107 }
108
109 template <class Operator>
110 void
112 apply(VectorType& x, VectorType& rhs, double reduction, Dune::InverseOperatorResult& res)
113 {
114 if (direct_solver_) {
115 auto* direct_precond = dynamic_cast<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>*>(preconditioner_.get());
116 if (direct_precond && direct_precond->needsRebuild()) {
117 recreateDirectSolver();
118 direct_precond->resetNeedsRebuild();
119 }
120 }
121 linsolver_->apply(x, rhs, reduction, res);
122 }
123
125 template <class Operator>
126 auto
129 {
130 return *preconditioner_;
131 }
132
133 template <class Operator>
134 Dune::SolverCategory::Category
136 category() const
137 {
138 return linearoperator_for_solver_->category();
139 }
140
141 // Machinery for making sequential or parallel operators/preconditioners/scalar products.
142 template <class Operator>
143 template <class Comm>
144 void
146 initOpPrecSp(Operator& op,
147 const Opm::PropertyTree& prm,
148 const std::function<VectorType()> weightsCalculator,
149 const Comm& comm,
150 std::size_t pressureIndex)
151 {
152 // Parallel case.
153 linearoperator_for_solver_ = &op;
154 const std::string solver_type = prm.get<std::string>("solver", "bicgstab");
155 auto child = prm.get_child_optional("preconditioner");
156 if (solver_type == "umfpack") {
157 preconditioner_ = std::make_shared<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>>(
158 linearoperator_for_solver_->category());
159 } else {
161 child ? *child : Opm::PropertyTree(),
162 weightsCalculator,
163 comm,
164 pressureIndex);
165 }
166 scalarproduct_ = Dune::createScalarProduct<VectorType, Comm>(comm, op.category());
167 }
168
169 template <class Operator>
170 void
171 FlexibleSolver<Operator>::
172 initOpPrecSp(Operator& op,
173 const Opm::PropertyTree& prm,
174 const std::function<VectorType()> weightsCalculator,
175 const Dune::Amg::SequentialInformation&,
176 std::size_t pressureIndex)
177 {
178 // Sequential case.
179 linearoperator_for_solver_ = &op;
180 const std::string solver_type = prm.get<std::string>("solver", "bicgstab");
181 auto child = prm.get_child_optional("preconditioner");
182 if (solver_type == "umfpack") {
183 preconditioner_ = std::make_shared<Dune::DirectSolverUpdatePreconditioner<VectorType, VectorType>>(
184 linearoperator_for_solver_->category());
185 } else {
187 child ? *child : Opm::PropertyTree(),
188 weightsCalculator,
189 pressureIndex);
190 }
191 scalarproduct_ = std::make_shared<Dune::SeqScalarProduct<VectorType>>();
192 }
193
194
195 template <class Operator>
196 template <class Comm>
197 void
198 FlexibleSolver<Operator>::
199 initSolver(const Opm::PropertyTree& prm, const Comm& comm)
200 {
201 const bool is_iorank = comm.communicator().rank() == 0;
202 const double tol = prm.get<double>("tol", 1e-2);
203 const int maxiter = prm.get<int>("maxiter", 200);
204 const int verbosity = is_iorank ? prm.get<int>("verbosity", 0) : 0;
205 const std::string solver_type = prm.get<std::string>("solver", "bicgstab");
206
207
208 // make sure it is nullptr at the start (used for error checking in the end).
209 // while the linSolver_ is initalized as a nullptr, we want to make sure it is reset here,
210 // simply because we will check if it is at the end of this function and need to keep this invariant
211 // (that it is nullptr at the start of this function).
212 linsolver_.reset();
213 direct_solver_ = false;
214 if (solver_type == "bicgstab") {
215 linsolver_ = std::make_shared<Dune::BiCGSTABSolver<VectorType>>(*linearoperator_for_solver_,
216 *scalarproduct_,
217 *preconditioner_,
218 tol, // desired residual reduction factor
219 maxiter, // maximum number of iterations
220 verbosity);
221#if HAVE_AVX2_EXTENSION
222 } else if (solver_type == "mixed-bicgstab") {
223 if constexpr (Opm::is_gpu_operator_v<Operator>) {
224 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for GPU operators");
225 } else if constexpr (Opm::detail::is_multi_type_block_vector_v<VectorType>) {
226 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for multi-type block vectors.");
227 } else if constexpr (std::is_same_v<typename VectorType::field_type, float>){
228 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for single precision.");
229 } else {
230 const std::string prec_type = prm.get<std::string>("preconditioner.type", "error");
231 bool use_mixed_dilu= (prec_type=="legacy-mixed-dilu");
232 using MatrixType = decltype(linearoperator_for_solver_->getmat());
233 linsolver_ = std::make_shared<Dune::MixedSolver<VectorType,MatrixType>>(
234 linearoperator_for_solver_->getmat(),
235 tol,
236 maxiter,
237 use_mixed_dilu
238 );
239 }
240 // MixedBiCGSTABSolver starts here
241 } else if (solver_type == "mixed-precision") {
242 if constexpr (Opm::is_gpu_operator_v<Operator>) {
243 OPM_THROW(std::invalid_argument, "mixed-precision solver not supported for GPU operators");
244 } else if constexpr (Opm::detail::is_multi_type_block_vector_v<VectorType>) {
245 OPM_THROW(std::invalid_argument, "mixed-bicgstab solver not supported for multi-type block vectors.");
246 } else if constexpr (std::is_same_v<typename VectorType::field_type, float>){
247 OPM_THROW(std::invalid_argument, "mixed-precision solver not supported for single precision.");
248 } else {
249 linsolver_ = std::make_shared<Dune::MixedBiCGSTABSolver<Comm,Operator,VectorType>>(linearoperator_for_solver_,
250 scalarproduct_,
251 preconditioner_,
252 tol, // desired residual reduction factor
253 maxiter, // maximum number of iterations
254 verbosity,
255 comm);
256 }
257#endif
258 } else if (solver_type == "cg") {
259 linsolver_ = std::make_shared<Dune::CGSolver<VectorType>>(*linearoperator_for_solver_,
260 *scalarproduct_,
261 *preconditioner_,
262 tol, // desired residual reduction factor
263 maxiter, // maximum number of iterations
264 verbosity);
265 } else if (solver_type == "loopsolver") {
266 linsolver_ = std::make_shared<Dune::LoopSolver<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 == "gmres") {
273 int restart = prm.get<int>("restart", 15);
274 linsolver_ = std::make_shared<Dune::RestartedGMResSolver<VectorType>>(*linearoperator_for_solver_,
275 *scalarproduct_,
276 *preconditioner_,
277 tol,// desired residual reduction factor
278 restart,
279 maxiter, // maximum number of iterations
280 verbosity);
281 } else if (solver_type == "flexgmres") {
282 if constexpr (Opm::is_gpu_operator_v<Operator>) {
283 OPM_THROW(std::invalid_argument, "flexgmres solver not supported for GPU operators.");
284 } else {
285 int restart = prm.get<int>("restart", 15);
286 linsolver_ = std::make_shared<Dune::RestartedFlexibleGMResSolver<VectorType>>(*linearoperator_for_solver_,
287 *scalarproduct_,
288 *preconditioner_,
289 tol,// desired residual reduction factor
290 restart,
291 maxiter, // maximum number of iterations
292 verbosity);
293 }
294 } else if (solver_type == "preconditioner2inverseoperator") {
295 if (!preconditioner_) {
296 OPM_THROW(std::invalid_argument,
297 "Properties: Solver preconditioner2inverseoperator requires a preconditioner.");
298 }
299 linsolver_ = std::make_shared<Dune::Preconditioner2InverseOperator<VectorType>>(preconditioner_);
300 } else {
301 if constexpr (!Opm::is_gpu_operator_v<Operator> && !Opm::detail::is_multi_type_block_vector_v<VectorType>) {
302#if HAVE_SUITESPARSE_UMFPACK
303 if (solver_type == "umfpack") {
304 if constexpr (std::is_same_v<typename VectorType::field_type,float>) {
305 OPM_THROW(std::invalid_argument, "UMFPack cannot be used with floats");
306 } else {
307 using MatrixType = std::remove_const_t<std::remove_reference_t<decltype(linearoperator_for_solver_->getmat())>>;
308 linsolver_ = std::make_shared<Dune::UMFPack<MatrixType>>(linearoperator_for_solver_->getmat(), verbosity, false);
309 direct_solver_ = true;
310 }
311#endif
312#if HAVE_CUDA
313 } else if (solver_type == "gpubicgstab") {
315 *linearoperator_for_solver_,
316 *scalarproduct_,
317 preconditioner_,
318 tol, // desired residual reduction factor
319 maxiter, // maximum number of iterations
320 verbosity,
321 comm));
322 #endif
323 }
324 }
325 }
326 if (!linsolver_) {
327 OPM_THROW(std::invalid_argument,
328 "Properties: Solver " + solver_type + " not known.");
329 }
330 }
331
332
333 // For now, the only direct solver we support is UMFPACK from SuiteSparse.
334 // When the matrix is updated (keeping sparsity pattern) it is possible to
335 // exploit separation of symbolic and numeric factorization, but we do not
336 // do so at this point. For complete generality, the solver abstract class
337 // Dune::InverseOperator<> should be extended with an update() function.
338 template <class Operator>
339 void
340 FlexibleSolver<Operator>::
341 recreateDirectSolver()
342 {
343#if HAVE_SUITESPARSE_UMFPACK
344 if constexpr (!Opm::is_gpu_operator_v<Operator> && !Opm::detail::is_multi_type_block_vector_v<VectorType>) {
345 if constexpr (std::is_same_v<typename VectorType::field_type, float>) {
346 OPM_THROW(std::invalid_argument, "UMFPack cannot be used with floats");
347 } else {
348 using MatrixType = std::remove_const_t<std::remove_reference_t<decltype(linearoperator_for_solver_->getmat())>>;
349 linsolver_ = std::make_shared<Dune::UMFPack<MatrixType>>(linearoperator_for_solver_->getmat(), 0, false);
350 }
351 }
352#else
353 OPM_THROW(std::logic_error, "Direct solver specified, but the FlexibleSolver class was not compiled with SuiteSparse support.");
354#endif
355 }
356
357
358 // Main initialization routine.
359 // Call with Comm == Dune::Amg::SequentialInformation to get a serial solver.
360 template <class Operator>
361 template <class Comm>
362 void
364 init(Operator& op,
365 const Comm& comm,
366 const Opm::PropertyTree& prm,
367 const std::function<VectorType()> weightsCalculator,
368 std::size_t pressureIndex)
369 {
370 initOpPrecSp(op, prm, weightsCalculator, comm, pressureIndex);
371 initSolver(prm, comm);
372 }
373
374} // namespace Dune
375
376
377// Macros to simplify explicit instantiation of FlexibleSolver for various block sizes.
378
379// Vectors and matrices.
380template<class Scalar, int N>
381using BV = Dune::BlockVector<Dune::FieldVector<Scalar, N>>;
382template<class Scalar, int N>
383using OBM = Dune::BCRSMatrix<Opm::MatrixBlock<Scalar, N, N>>;
384
385// Sequential operators.
386template<class Scalar, int N>
387using SeqOpM = Dune::MatrixAdapter<OBM<Scalar,N>, BV<Scalar,N>, BV<Scalar,N>>;
388template<class Scalar, int N>
390
391#if HAVE_MPI
392
393// Parallel communicator and operators.
394using Comm = Dune::OwnerOverlapCopyCommunication<int, int>;
395template<class Scalar, int N>
397template<class Scalar, int N>
399template<class Scalar, int N>
400using ParOpD = Dune::OverlappingSchwarzOperator<OBM<Scalar,N>, BV<Scalar,N>, BV<Scalar,N>, Comm>;
401
402// Note: we must instantiate the constructor that is a template.
403// This is only needed in the parallel case, since otherwise the Comm type is
404// not a template argument but always SequentialInformation.
405
406#define INSTANTIATE_FLEXIBLESOLVER_OP(...) \
407 template class Dune::FlexibleSolver<__VA_ARGS__>; \
408 template Dune::FlexibleSolver<__VA_ARGS__>:: \
409 FlexibleSolver(__VA_ARGS__& op, \
410 const Comm& comm, \
411 const Opm::PropertyTree& prm, \
412 const std::function<typename __VA_ARGS__::domain_type()>& weightsCalculator, \
413 std::size_t pressureIndex);
414
415#define INSTANTIATE_FLEXIBLESOLVER(T,N) \
416 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpM<T,N>); \
417 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpW<T,N>); \
418 INSTANTIATE_FLEXIBLESOLVER_OP(ParOpM<T,N>); \
419 INSTANTIATE_FLEXIBLESOLVER_OP(ParOpW<T,N>); \
420 INSTANTIATE_FLEXIBLESOLVER_OP(ParOpD<T,N>);
421
422#else // HAVE_MPI
423
424#define INSTANTIATE_FLEXIBLESOLVER_OP(...) \
425 template class Dune::FlexibleSolver<__VA_ARGS__>;
426
427#define INSTANTIATE_FLEXIBLESOLVER(T,N) \
428 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpM<T,N>); \
429 INSTANTIATE_FLEXIBLESOLVER_OP(SeqOpW<T,N>);
430
431#endif // HAVE_MPI
432
433#endif // OPM_FLEXIBLE_SOLVER_IMPL_HEADER_INCLUDED
Dune::OverlappingSchwarzOperator< OBM< Scalar, N >, BV< Scalar, N >, BV< Scalar, N >, Comm > ParOpD
Definition: FlexibleSolver_impl.hpp:400
Dune::BCRSMatrix< Opm::MatrixBlock< Scalar, N, N > > OBM
Definition: FlexibleSolver_impl.hpp:383
Dune::BlockVector< Dune::FieldVector< Scalar, N > > BV
Definition: FlexibleSolver_impl.hpp:381
Dune::OwnerOverlapCopyCommunication< int, int > Comm
Definition: FlexibleSolver_impl.hpp:394
Dune::MatrixAdapter< OBM< Scalar, N >, BV< Scalar, N >, BV< Scalar, N > > SeqOpM
Definition: FlexibleSolver_impl.hpp:387
Definition: PreconditionerWithUpdate.hpp:98
Definition: FlexibleSolver.hpp:45
Dune::SolverCategory::Category category() const override
Definition: FlexibleSolver_impl.hpp:136
void apply(VectorType &x, VectorType &rhs, Dune::InverseOperatorResult &res) override
Definition: FlexibleSolver_impl.hpp:97
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:72
AbstractPrecondType & preconditioner()
Access the contained preconditioner.
Definition: FlexibleSolver_impl.hpp:128
Dune linear operator that assumes ghost rows are ordered after interior rows. Avoids some computation...
Definition: WellOperators.hpp:402
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:154
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:299
Adapter to combine a matrix and another linear operator into a combined linear operator.
Definition: WellOperators.hpp:225
Wraps a CUDA solver to work with CPU data.
Definition: gpuistl/SolverAdapter.hpp:52
Definition: fvbaseprimaryvariables.hh:161
Definition: alignedallocator.hh:32
constexpr bool is_multi_type_block_vector_v
Definition: FlexibleSolver_impl.hpp:56
Dune::InverseOperatorResult InverseOperatorResult
Definition: GpuBridge.hpp:32
Definition: FlexibleSolver_impl.hpp:52