Debian Codegraph @

dune/istl/ldl.hh

raw
1 // SPDX-FileCopyrightText: Copyright © DUNE Project contributors, see file LICENSE.md in module root
2 // SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception
3 // -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
4 // vi: set et ts=4 sw=2 sts=2:
5 #ifndef DUNE_ISTL_LDL_HH
6 #define DUNE_ISTL_LDL_HH
7
8 #if HAVE_SUITESPARSE_LDL || defined DOXYGEN
9
10 #include <iostream>
11 #include <memory>
12 #include <type_traits>
13
14 #ifdef __cplusplus
15 extern "C"
16 {
17 #include <ldl.h>
18 #include <amd.h>
19 }
20 #endif
21
22 #include <dune/common/exceptions.hh>
23
24 #include <dune/istl/bccsmatrixinitializer.hh>
25 #include <dune/istl/solvers.hh>
26 #include <dune/istl/solvertype.hh>
27 #include <dune/istl/solverregistry.hh>
28
29 namespace Dune {
30 /**
31 * @addtogroup ISTL
32 *
33 * @{
34 */
35 /**
36 * @file
37 * @author Marco Agnese, Andrea Sacconi
38 * @brief Class for using LDL with ISTL matrices.
39 */
40
41 // forward declarations
42 template<class M, class T, class TM, class TD, class TA>
43 class SeqOverlappingSchwarz;
44
45 template<class T, bool tag>
46 struct SeqOverlappingSchwarzAssemblerHelper;
47
48 /**
49 * @brief Use the %LDL package to directly solve linear systems -- empty default class
50 * @tparam Matrix the matrix type defining the system
51 * Details on UMFPack can be found on
52 * http://www.cise.ufl.edu/research/sparse/ldl/
53 */
54 template<class Matrix>
55 class LDL
56 {};
57
58 /**
59 * @brief The %LDL direct sparse solver for matrices of type BCRSMatrix
60 *
61 * Specialization for the Dune::BCRSMatrix. %LDL will always go double
62 * precision.
63 *
64 * \tparam T Number type. Only double is supported
65 * \tparam A STL-compatible allocator type
66 * \tparam n Number of rows in a matrix block
67 * \tparam m Number of columns in a matrix block
68 *
69 * \note This will only work if dune-istl has been configured to use LDL
70 */
71 template<typename T, typename A, int n, int m>
72 class LDL<BCRSMatrix<FieldMatrix<T,n,m>,A > >
73 : public InverseOperator<BlockVector<FieldVector<T,m>, typename std::allocator_traits<A>::template rebind_alloc<FieldVector<T,m> > >,
74 BlockVector<FieldVector<T,n>, typename std::allocator_traits<A>::template rebind_alloc<FieldVector<T,n> > > >
75 {
76 public:
77 /** @brief The matrix type. */
78 typedef Dune::BCRSMatrix<FieldMatrix<T,n,m>,A> Matrix;
79 typedef Dune::BCRSMatrix<FieldMatrix<T,n,m>,A> matrix_type;
80 /** @brief The corresponding SuperLU Matrix type. */
81 typedef Dune::ISTL::Impl::BCCSMatrix<T,int> LDLMatrix;
82 /** @brief Type of an associated initializer class. */
83 typedef ISTL::Impl::BCCSMatrixInitializer<BCRSMatrix<FieldMatrix<T,n,m>,A>, int> MatrixInitializer;
84 /** @brief The type of the domain of the solver. */
85 typedef Dune::BlockVector<FieldVector<T,m>, typename std::allocator_traits<A>::template rebind_alloc<FieldVector<T,m> > > domain_type;
86 /** @brief The type of the range of the solver. */
87 typedef Dune::BlockVector<FieldVector<T,n>, typename std::allocator_traits<A>::template rebind_alloc<FieldVector<T,n> > > range_type;
88
89 //! Category of the solver (see SolverCategory::Category)
90 SolverCategory::Category category() const override
91 {
92 return SolverCategory::Category::sequential;
93 }
94
95 /**
96 * @brief Construct a solver object from a BCRSMatrix.
97 *
98 * This computes the matrix decomposition, and may take a long time
99 * (and use a lot of memory).
100 *
101 * @param matrix the matrix to solve for
102 * @param verbose 0 or 1 set the verbosity level, defaults to 0
103 */
104 LDL(const Matrix& matrix, int verbose=0) : matrixIsLoaded_(false), verbose_(verbose)
105 {
106 //check whether T is a supported type
107 static_assert(std::is_same<T,double>::value,"Unsupported Type in LDL (only double supported)");
108 setMatrix(matrix);
109 }
110
111 /**
112 * @brief Constructor for compatibility with SuperLU standard constructor
113 *
114 * This computes the matrix decomposition, and may take a long time
115 * (and use a lot of memory).
116 *
117 * @param matrix the matrix to solve for
118 * @param verbose 0 or 1 set the verbosity level, defaults to 0
119 */
120 LDL(const Matrix& matrix, int verbose, bool) : matrixIsLoaded_(false), verbose_(verbose)
121 {
122 //check whether T is a supported type
123 static_assert(std::is_same<T,double>::value,"Unsupported Type in LDL (only double supported)");
124 setMatrix(matrix);
125 }
126
127 /** @brief Constructs the LDL solver.
128 *
129 * @param matrix The matrix of the system to solve.
130 * @param config ParameterTree containing solver parameters.
131 *
132 * ParameterTree Key | Meaning
133 * ------------------|------------
134 * verbose | The verbosity level. default=0
135 */
136 LDL(const Matrix& matrix, const ParameterTree& config)
137 : LDL(matrix, config.get<int>("verbose", 0))
138 {}
139
140 /** @brief Default constructor. */
141 LDL() : matrixIsLoaded_(false), verbose_(0)
142 {}
143
144 /** @brief Default constructor. */
145 virtual ~LDL()
146 {
147 if ((ldlMatrix_.N() + ldlMatrix_.M() > 0) || matrixIsLoaded_)
148 free();
149 }
150
151 /** \copydoc InverseOperator::apply(X&, Y&, InverseOperatorResult&) */
152 void apply(domain_type& x, range_type& b, InverseOperatorResult& res) override
153 {
154 const int dimMat(ldlMatrix_.N());
155 ldl_perm(dimMat, Y_, reinterpret_cast<double*>(&b[0]), P_);
156 ldl_lsolve(dimMat, Y_, Lp_, Li_, Lx_);
157 ldl_dsolve(dimMat, Y_, D_);
158 ldl_ltsolve(dimMat, Y_, Lp_, Li_, Lx_);
159 ldl_permt(dimMat, reinterpret_cast<double*>(&x[0]), Y_, P_);
160 // this is a direct solver
161 res.iterations = 1;
162 res.converged = true;
163 }
164
165 /** \copydoc InverseOperator::apply(X&,Y&,double,InverseOperatorResult&) */
166 void apply(domain_type& x, range_type& b, [[maybe_unused]] double reduction, InverseOperatorResult& res) override
167 {
168 apply(x,b,res);
169 }
170
171 /**
172 * @brief Additional apply method with c-arrays in analogy to superlu.
173 * @param x solution array
174 * @param b rhs array
175 */
176 void apply(T* x, T* b)
177 {
178 const int dimMat(ldlMatrix_.N());
179 ldl_perm(dimMat, Y_, b, P_);
180 ldl_lsolve(dimMat, Y_, Lp_, Li_, Lx_);
181 ldl_dsolve(dimMat, Y_, D_);
182 ldl_ltsolve(dimMat, Y_, Lp_, Li_, Lx_);
183 ldl_permt(dimMat, x, Y_, P_);
184 }
185
186 void setOption([[maybe_unused]] unsigned int option, [[maybe_unused]] double value)
187 {}
188
189 /** @brief Initialize data from given matrix. */
190 void setMatrix(const Matrix& matrix)
191 {
192 if ((ldlMatrix_.N() + ldlMatrix_.M() > 0) || matrixIsLoaded_)
193 free();
194
195 if (ldlMatrix_.N() + ldlMatrix_.M() + ldlMatrix_.nonzeroes() != 0)
196 ldlMatrix_.free();
197 ldlMatrix_.setSize(MatrixDimension<Matrix>::rowdim(matrix),
198 MatrixDimension<Matrix>::coldim(matrix));
199 ISTL::Impl::BCCSMatrixInitializer<Matrix, int> initializer(ldlMatrix_);
200
201 copyToBCCSMatrix(initializer, matrix);
202
203 decompose();
204 }
205
206 template<class S>
207 void setSubMatrix(const Matrix& matrix, const S& rowIndexSet)
208 {
209 if ((ldlMatrix_.N() + ldlMatrix_.M() > 0) || matrixIsLoaded_)
210 free();
211
212 if (ldlMatrix_.N() + ldlMatrix_.M() + ldlMatrix_.nonzeroes() != 0)
213 ldlMatrix_.free();
214
215 ldlMatrix_.setSize(rowIndexSet.size()*MatrixDimension<Matrix>::rowdim(matrix) / matrix.N(),
216 rowIndexSet.size()*MatrixDimension<Matrix>::coldim(matrix) / matrix.M());
217 ISTL::Impl::BCCSMatrixInitializer<Matrix, int> initializer(ldlMatrix_);
218
219 copyToBCCSMatrix(initializer, ISTL::Impl::MatrixRowSubset<Matrix,std::set<std::size_t> >(matrix,rowIndexSet));
220
221 decompose();
222 }
223
224 /**
225 * @brief Sets the verbosity level for the solver.
226 * @param v verbosity level: 0 only error messages, 1 a bit of statistics.
227 */
228 inline void setVerbosity(int v)
229 {
230 verbose_=v;
231 }
232
233 /**
234 * @brief Return the column compress matrix.
235 * @warning It is up to the user to keep consistency.
236 */
237 inline LDLMatrix& getInternalMatrix()
238 {
239 return ldlMatrix_;
240 }
241
242 /**
243 * @brief Free allocated space.
244 * @warning Later calling apply will result in an error.
245 */
246 void free()
247 {
248 delete [] D_;
249 delete [] Y_;
250 delete [] Lp_;
251 delete [] Lx_;
252 delete [] Li_;
253 delete [] P_;
254 delete [] Pinv_;
255 ldlMatrix_.free();
256 matrixIsLoaded_ = false;
257 }
258
259 /** @brief Get method name. */
260 inline const char* name()
261 {
262 return "LDL";
263 }
264
265 /**
266 * @brief Get factorization diagonal matrix D.
267 * @warning It is up to the user to preserve consistency.
268 */
269 inline double* getD()
270 {
271 return D_;
272 }
273
274 /**
275 * @brief Get factorization Lp.
276 * @warning It is up to the user to preserve consistency.
277 */
278 inline int* getLp()
279 {
280 return Lp_;
281 }
282
283 /**
284 * @brief Get factorization Li.
285 * @warning It is up to the user to preserve consistency.
286 */
287 inline int* getLi()
288 {
289 return Li_;
290 }
291
292 /**
293 * @brief Get factorization Lx.
294 * @warning It is up to the user to preserve consistency.
295 */
296 inline double* getLx()
297 {
298 return Lx_;
299 }
300
301 private:
302 template<class M,class X, class TM, class TD, class T1>
303 friend class SeqOverlappingSchwarz;
304
305 friend struct SeqOverlappingSchwarzAssemblerHelper<LDL<Matrix>,true>;
306
307 /** @brief Computes the LDL decomposition. */
308 void decompose()
309 {
310 // allocate vectors
311 const int dimMat(ldlMatrix_.N());
312 D_ = new double [dimMat];
313 Y_ = new double [dimMat];
314 Lp_ = new int [dimMat + 1];
315 Parent_ = new int [dimMat];
316 Lnz_ = new int [dimMat];
317 Flag_ = new int [dimMat];
318 Pattern_ = new int [dimMat];
319 P_ = new int [dimMat];
320 Pinv_ = new int [dimMat];
321
322 double Info [AMD_INFO];
323 if(amd_order (dimMat, ldlMatrix_.getColStart(), ldlMatrix_.getRowIndex(), P_, (double *) NULL, Info) < AMD_OK)
324 DUNE_THROW(InvalidStateException,"Error: AMD failed!");
325 if(verbose_ > 0)
326 amd_info (Info);
327 // compute the symbolic factorisation
328 ldl_symbolic(dimMat, ldlMatrix_.getColStart(), ldlMatrix_.getRowIndex(), Lp_, Parent_, Lnz_, Flag_, P_, Pinv_);
329 // initialise those entries of additionalVectors_ whose dimension is known only now
330 Lx_ = new double [Lp_[dimMat]];
331 Li_ = new int [Lp_[dimMat]];
332 // compute the numeric factorisation
333 const int rank(ldl_numeric(dimMat, ldlMatrix_.getColStart(), ldlMatrix_.getRowIndex(), ldlMatrix_.getValues(),
334 Lp_, Parent_, Lnz_, Li_, Lx_, D_, Y_, Pattern_, Flag_, P_, Pinv_));
335 // free temporary vectors
336 delete [] Flag_;
337 delete [] Pattern_;
338 delete [] Parent_;
339 delete [] Lnz_;
340
341 if(rank!=dimMat)
342 DUNE_THROW(InvalidStateException,"Error: LDL factorisation failed!");
343 }
344
345 LDLMatrix ldlMatrix_;
346 bool matrixIsLoaded_;
347 int verbose_;
348 int* Lp_;
349 int* Parent_;
350 int* Lnz_;
351 int* Flag_;
352 int* Pattern_;
353 int* P_;
354 int* Pinv_;
355 double* D_;
356 double* Y_;
357 double* Lx_;
358 int* Li_;
359 };
360
361 template<typename T, typename A, int n, int m>
362 struct IsDirectSolver<LDL<BCRSMatrix<FieldMatrix<T,n,m>,A> > >
363 {
364 enum {value = true};
365 };
366
367 template<typename T, typename A, int n, int m>
368 struct StoresColumnCompressed<LDL<BCRSMatrix<FieldMatrix<T,n,m>,A> > >
369 {
370 enum {value = true};
371 };
372
373 DUNE_REGISTER_SOLVER("ldl",
374 [](auto opTraits, const auto& op, const Dune::ParameterTree& config)
375 -> std::shared_ptr<typename decltype(opTraits)::solver_type>
376 {
377 using OpTraits = decltype(opTraits);
378 using M = typename OpTraits::matrix_type;
379 // works only for sequential operators
380 if constexpr (OpTraits::isParallel){
381 if(opTraits.getCommOrThrow(op).communicator().size() > 1)
382 DUNE_THROW(Dune::InvalidStateException, "LDL works only for sequential operators.");
383 }
384 // check if LDL<M>* is convertible to
385 // InverseOperator*. This allows only the explicit
386 // specialized variants of LDL
387 if constexpr (std::is_convertible_v<LDL<M>*,
388 Dune::InverseOperator<typename OpTraits::domain_type,
389 typename OpTraits::range_type>*> &&
390 std::is_same_v<typename FieldTraits<M>::field_type, double>
391 ){
392 const auto& A = opTraits.getAssembledOpOrThrow(op);
393 const M& mat = A->getmat();
394 int verbose = config.get("verbose", 0);
395 return std::make_shared<LDL<M>>(mat,verbose);
396 }
397 DUNE_THROW(UnsupportedType,
398 "Unsupported Type in LDL (only FieldMatrix<double,...> supported)");
399 });
400
401 } // end namespace Dune
402
403
404 #endif //HAVE_SUITESPARSE_LDL
405 #endif //DUNE_ISTL_LDL_HH