Debian Codegraph @

dune/istl/umfpack.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_UMFPACK_HH
6 #define DUNE_ISTL_UMFPACK_HH
7
8 #if HAVE_SUITESPARSE_UMFPACK || defined DOXYGEN
9
10 #include<complex>
11 #include<type_traits>
12
13 #include<umfpack.h>
14
15 #include<dune/common/exceptions.hh>
16 #include<dune/common/fmatrix.hh>
17 #include<dune/common/fvector.hh>
18 #include<dune/istl/bccsmatrixinitializer.hh>
19 #include<dune/istl/bcrsmatrix.hh>
20 #include<dune/istl/matrix.hh>
21 #include<dune/istl/foreach.hh>
22 #include<dune/istl/multitypeblockmatrix.hh>
23 #include<dune/istl/multitypeblockvector.hh>
24 #include<dune/istl/solvers.hh>
25 #include<dune/istl/solvertype.hh>
26 #include <dune/istl/solverfactory.hh>
27
28
29
30 namespace Dune {
31 /**
32 * @addtogroup ISTL
33 *
34 * @{
35 */
36 /**
37 * @file
38 * @author Dominic Kempf
39 * @brief Classes for using UMFPack with ISTL matrices.
40 */
41
42 // FORWARD DECLARATIONS
43 template<class M, class T, class TM, class TD, class TA>
44 class SeqOverlappingSchwarz;
45
46 template<class T, bool tag>
47 struct SeqOverlappingSchwarzAssemblerHelper;
48
49 // wrapper class for C-Function Calls in the backend. Choose the right function namespace
50 // depending on the template parameter used.
51 template<typename T>
52 struct UMFPackMethodChooser
53 {
54 static constexpr bool valid = false ;
55 };
56
57 template<>
58 struct UMFPackMethodChooser<double>
59 {
60 static constexpr bool valid = true ;
61
62 template<typename... A>
63 static void defaults(A... args)
64 {
65 umfpack_dl_defaults(args...);
66 }
67 template<typename... A>
68 static void free_numeric(A... args)
69 {
70 umfpack_dl_free_numeric(args...);
71 }
72 template<typename... A>
73 static void free_symbolic(A... args)
74 {
75 umfpack_dl_free_symbolic(args...);
76 }
77 template<typename... A>
78 static int load_numeric(A... args)
79 {
80 return umfpack_dl_load_numeric(args...);
81 }
82 template<typename... A>
83 static void numeric(A... args)
84 {
85 umfpack_dl_numeric(args...);
86 }
87 template<typename... A>
88 static void report_info(A... args)
89 {
90 umfpack_dl_report_info(args...);
91 }
92 template<typename... A>
93 static void report_status(A... args)
94 {
95 umfpack_dl_report_status(args...);
96 }
97 template<typename... A>
98 static int save_numeric(A... args)
99 {
100 return umfpack_dl_save_numeric(args...);
101 }
102 template<typename... A>
103 static void solve(A... args)
104 {
105 umfpack_dl_solve(args...);
106 }
107 template<typename... A>
108 static void symbolic(A... args)
109 {
110 umfpack_dl_symbolic(args...);
111 }
112 };
113
114 template<>
115 struct UMFPackMethodChooser<std::complex<double> >
116 {
117 static constexpr bool valid = true ;
118 using size_type = SuiteSparse_long;
119
120 template<typename... A>
121 static void defaults(A... args)
122 {
123 umfpack_zl_defaults(args...);
124 }
125 template<typename... A>
126 static void free_numeric(A... args)
127 {
128 umfpack_zl_free_numeric(args...);
129 }
130 template<typename... A>
131 static void free_symbolic(A... args)
132 {
133 umfpack_zl_free_symbolic(args...);
134 }
135 template<typename... A>
136 static int load_numeric(A... args)
137 {
138 return umfpack_zl_load_numeric(args...);
139 }
140 template<typename... A>
141 static void numeric(const size_type* cs, const size_type* ri, const double* val, A... args)
142 {
143 umfpack_zl_numeric(cs,ri,val,NULL,args...);
144 }
145 template<typename... A>
146 static void report_info(A... args)
147 {
148 umfpack_zl_report_info(args...);
149 }
150 template<typename... A>
151 static void report_status(A... args)
152 {
153 umfpack_zl_report_status(args...);
154 }
155 template<typename... A>
156 static int save_numeric(A... args)
157 {
158 return umfpack_zl_save_numeric(args...);
159 }
160 template<typename... A>
161 static void solve(size_type m, const size_type* cs, const size_type* ri, std::complex<double>* val, double* x, const double* b,A... args)
162 {
163 const double* cval = reinterpret_cast<const double*>(val);
164 umfpack_zl_solve(m,cs,ri,cval,NULL,x,NULL,b,NULL,args...);
165 }
166 template<typename... A>
167 static void symbolic(size_type m, size_type n, const size_type* cs, const size_type* ri, const double* val, A... args)
168 {
169 umfpack_zl_symbolic(m,n,cs,ri,val,NULL,args...);
170 }
171 };
172
173 namespace Impl
174 {
175 template<class M, class = void>
176 struct UMFPackVectorChooser;
177
178 /** @brief The type of the domain of the solver */
179 template<class M> using UMFPackDomainType = typename UMFPackVectorChooser<M>::domain_type;
180
181 /** @brief The type of the range of the solver */
182 template<class M> using UMFPackRangeType = typename UMFPackVectorChooser<M>::range_type;
183
184 template<class M>
185 struct UMFPackVectorChooser<M,
186 std::enable_if_t<(std::is_same<M,double>::value) || (std::is_same<M,std::complex<double> >::value)>>
187 {
188 using domain_type = M;
189 using range_type = M;
190 };
191
192 template<typename T, int n, int m>
193 struct UMFPackVectorChooser<FieldMatrix<T,n,m>,
194 std::enable_if_t<(std::is_same<T,double>::value) || (std::is_same<T,std::complex<double> >::value)>>
195 {
196 /** @brief The type of the domain of the solver */
197 using domain_type = FieldVector<T,m>;
198 /** @brief The type of the range of the solver */
199 using range_type = FieldVector<T,n>;
200 };
201
202 template<typename T, typename A>
203 struct UMFPackVectorChooser<BCRSMatrix<T,A>,
204 std::void_t<UMFPackDomainType<T>, UMFPackRangeType<T>>>
205 {
206 // In case of recursive deduction (e.g., BCRSMatrix<FieldMatrix<...>, Allocator<FieldMatrix<...>>>)
207 // the allocator needs to be converted to the sub-block allocator type too (e.g., Allocator<FieldVector<...>>).
208 // Note that matrix allocator is assumed to be the same as the domain/range type of allocators
209 /** @brief The type of the domain of the solver */
210 using domain_type = BlockVector<UMFPackDomainType<T>, typename std::allocator_traits<A>::template rebind_alloc<UMFPackDomainType<T>>>;
211 /** @brief The type of the range of the solver */
212 using range_type = BlockVector<UMFPackRangeType<T>, typename std::allocator_traits<A>::template rebind_alloc<UMFPackRangeType<T>>>;
213 };
214
215 template<typename T, typename A>
216 struct UMFPackVectorChooser<Matrix<T,A>,
217 std::void_t<UMFPackDomainType<T>, UMFPackRangeType<T>>>
218 : public UMFPackVectorChooser<BCRSMatrix<T,A>, std::void_t<UMFPackDomainType<T>, UMFPackRangeType<T>>>
219 {};
220
221 // to make the `UMFPackVectorChooser` work with `MultiTypeBlockMatrix`, we need to add an intermediate step for the rows, which are typically `MultiTypeBlockVector`
222 template<typename FirstBlock, typename... Blocks>
223 struct UMFPackVectorChooser<MultiTypeBlockVector<FirstBlock, Blocks...>,
224 std::void_t<UMFPackDomainType<FirstBlock>, UMFPackRangeType<FirstBlock>, UMFPackDomainType<Blocks>...>>
225 {
226 /** @brief The type of the domain of the solver */
227 using domain_type = MultiTypeBlockVector<UMFPackDomainType<FirstBlock>, UMFPackDomainType<Blocks>...>;
228 /** @brief The type of the range of the solver */
229 using range_type = UMFPackRangeType<FirstBlock>;
230 };
231
232 // specialization for `MultiTypeBlockMatrix` with `MultiTypeBlockVector` rows
233 template<typename FirstRow, typename... Rows>
234 struct UMFPackVectorChooser<MultiTypeBlockMatrix<FirstRow, Rows...>,
235 std::void_t<UMFPackDomainType<FirstRow>, UMFPackRangeType<FirstRow>, UMFPackRangeType<Rows>...>>
236 {
237 /** @brief The type of the domain of the solver */
238 using domain_type = UMFPackDomainType<FirstRow>;
239 /** @brief The type of the range of the solver */
240 using range_type = MultiTypeBlockVector< UMFPackRangeType<FirstRow>, UMFPackRangeType<Rows>... >;
241 };
242
243 // dummy class to represent no BitVector
244 struct NoBitVector
245 {};
246
247
248 }
249
250 /** @brief The %UMFPack direct sparse solver
251 *
252 * Details on UMFPack can be found on
253 * http://www.cise.ufl.edu/research/sparse/umfpack/
254 *
255 * %UMFPack will always use double precision.
256 * For complex matrices use a matrix type with std::complex<double>
257 * as the underlying number type.
258 *
259 * \tparam Matrix the matrix type defining the system
260 *
261 * \note This will only work if dune-istl has been configured to use UMFPack
262 */
263 template<typename M>
264 class UMFPack : public InverseOperator<Impl::UMFPackDomainType<M>,Impl::UMFPackRangeType<M>>
265 {
266 using T = typename M::field_type;
267
268 public:
269 using size_type = SuiteSparse_long;
270
271 /** @brief The matrix type. */
272 using Matrix = M;
273 using matrix_type = M;
274 /** @brief The corresponding (scalar) UMFPack matrix type.*/
275 using UMFPackMatrix = ISTL::Impl::BCCSMatrix<typename Matrix::field_type, size_type>;
276 /** @brief Type of an associated initializer class. */
277 using MatrixInitializer = ISTL::Impl::BCCSMatrixInitializer<M, size_type>;
278 /** @brief The type of the domain of the solver. */
279 using domain_type = Impl::UMFPackDomainType<M>;
280 /** @brief The type of the range of the solver. */
281 using range_type = Impl::UMFPackRangeType<M>;
282
283 //! Category of the solver (see SolverCategory::Category)
284 SolverCategory::Category category() const override
285 {
286 return SolverCategory::Category::sequential;
287 }
288
289 /** @brief Construct a solver object from a matrix
290 *
291 * This computes the matrix decomposition, and may take a long time
292 * (and use a lot of memory).
293 *
294 * @param matrix the matrix to solve for
295 * @param verbose [0..2] set the verbosity level, defaults to 0
296 */
297 UMFPack(const Matrix& matrix, int verbose=0) : matrixIsLoaded_(false)
298 {
299 //check whether T is a supported type
300 static_assert((std::is_same<T,double>::value) || (std::is_same<T,std::complex<double> >::value),
301 "Unsupported Type in UMFPack (only double and std::complex<double> supported)");
302 Caller::defaults(UMF_Control);
303 setVerbosity(verbose);
304 setMatrix(matrix);
305 }
306
307 /** @brief Constructor for compatibility with SuperLU standard constructor
308 *
309 * This computes the matrix decomposition, and may take a long time
310 * (and use a lot of memory).
311 *
312 * @param matrix the matrix to solve for
313 * @param verbose [0..2] set the verbosity level, defaults to 0
314 */
315 UMFPack(const Matrix& matrix, int verbose, bool) : matrixIsLoaded_(false)
316 {
317 //check whether T is a supported type
318 static_assert((std::is_same<T,double>::value) || (std::is_same<T,std::complex<double> >::value),
319 "Unsupported Type in UMFPack (only double and std::complex<double> supported)");
320 Caller::defaults(UMF_Control);
321 setVerbosity(verbose);
322 setMatrix(matrix);
323 }
324
325 /** @brief Construct a solver object from a matrix
326 *
327 * @param mat_ the matrix to solve for
328 * @param config ParameterTree containing solver parameters.
329 *
330 * ParameterTree Key | Meaning
331 * ------------------|------------
332 * verbose | The verbosity level. default=0
333 */
334 UMFPack(const Matrix& mat_, const ParameterTree& config)
335 : UMFPack(mat_, config.get<int>("verbose", 0))
336 {}
337
338 /** @brief default constructor
339 */
340 UMFPack() : matrixIsLoaded_(false), verbosity_(0)
341 {
342 //check whether T is a supported type
343 static_assert((std::is_same<T,double>::value) || (std::is_same<T,std::complex<double> >::value),
344 "Unsupported Type in UMFPack (only double and std::complex<double> supported)");
345 Caller::defaults(UMF_Control);
346 }
347
348 /** @brief Try loading a decomposition from file and do a decomposition if unsuccessful
349 * @param mat_ the matrix to decompose when no decoposition file found
350 * @param file the decomposition file
351 * @param verbose the verbosity level
352 *
353 * Use saveDecomposition(char* file) for manually storing a decomposition. This constructor
354 * will decompose mat_ and store the result to file if no file wasn't found in the first place.
355 * Thus, if you always use this you will only compute the decomposition once (and when you manually
356 * deleted the decomposition file).
357 */
358 UMFPack(const Matrix& mat_, const char* file, int verbose=0)
359 {
360 //check whether T is a supported type
361 static_assert((std::is_same<T,double>::value) || (std::is_same<T,std::complex<double> >::value),
362 "Unsupported Type in UMFPack (only double and std::complex<double> supported)");
363 Caller::defaults(UMF_Control);
364 setVerbosity(verbose);
365 int errcode = Caller::load_numeric(&UMF_Numeric, const_cast<char*>(file));
366 if ((errcode == UMFPACK_ERROR_out_of_memory) || (errcode == UMFPACK_ERROR_file_IO))
367 {
368 matrixIsLoaded_ = false;
369 setMatrix(mat_);
370 saveDecomposition(file);
371 }
372 else
373 {
374 matrixIsLoaded_ = true;
375 std::cout << "UMFPack decomposition successfully loaded from " << file << std::endl;
376 }
377 }
378
379 /** @brief try loading a decomposition from file
380 * @param file the decomposition file
381 * @param verbose the verbosity level
382 * @throws Dune::Exception When not being able to load the file. Does not need knowledge of the
383 * actual matrix!
384 */
385 UMFPack(const char* file, int verbose=0)
386 {
387 //check whether T is a supported type
388 static_assert((std::is_same<T,double>::value) || (std::is_same<T,std::complex<double> >::value),
389 "Unsupported Type in UMFPack (only double and std::complex<double> supported)");
390 Caller::defaults(UMF_Control);
391 int errcode = Caller::load_numeric(&UMF_Numeric, const_cast<char*>(file));
392 if (errcode == UMFPACK_ERROR_out_of_memory)
393 DUNE_THROW(Dune::Exception, "ran out of memory while loading UMFPack decomposition");
394 if (errcode == UMFPACK_ERROR_file_IO)
395 DUNE_THROW(Dune::Exception, "IO error while loading UMFPack decomposition");
396 matrixIsLoaded_ = true;
397 std::cout << "UMFPack decomposition successfully loaded from " << file << std::endl;
398 setVerbosity(verbose);
399 }
400
401 virtual ~UMFPack()
402 {
403 if ((umfpackMatrix_.N() + umfpackMatrix_.M() > 0) || matrixIsLoaded_)
404 free();
405 }
406
407 /**
408 * \copydoc InverseOperator::apply(X&, Y&, InverseOperatorResult&)
409 */
410 void apply(domain_type& x, range_type& b, InverseOperatorResult& res) override
411 {
412 if (umfpackMatrix_.N() != b.dim())
413 DUNE_THROW(Dune::ISTLError, "Size of right-hand-side vector b does not match the number of matrix rows!");
414 if (umfpackMatrix_.M() != x.dim())
415 DUNE_THROW(Dune::ISTLError, "Size of solution vector x does not match the number of matrix columns!");
416 if (b.size() == 0)
417 return;
418
419 // we have to convert x and b into flat structures
420 // however, this is linear in time
421 std::vector<T> xFlat(x.dim()), bFlat(b.dim());
422
423 flatVectorForEach(x, [&](auto&& entry, auto&& offset)
424 {
425 xFlat[ offset ] = entry;
426 });
427
428 flatVectorForEach(b, [&](auto&& entry, auto&& offset)
429 {
430 bFlat[ offset ] = entry;
431 });
432
433 double UMF_Apply_Info[UMFPACK_INFO];
434 Caller::solve(UMFPACK_A,
435 umfpackMatrix_.getColStart(),
436 umfpackMatrix_.getRowIndex(),
437 umfpackMatrix_.getValues(),
438 reinterpret_cast<double*>(&xFlat[0]),
439 reinterpret_cast<double*>(&bFlat[0]),
440 UMF_Numeric,
441 UMF_Control,
442 UMF_Apply_Info);
443
444 // copy back to blocked vector
445 flatVectorForEach(x, [&](auto&& entry, auto offset)
446 {
447 entry = xFlat[offset];
448 });
449
450 //this is a direct solver
451 res.iterations = 1;
452 res.converged = true;
453 res.elapsed = UMF_Apply_Info[UMFPACK_SOLVE_WALLTIME];
454
455 printOnApply(UMF_Apply_Info);
456 }
457
458 /**
459 * \copydoc InverseOperator::apply(X&,Y&,double,InverseOperatorResult&)
460 */
461 void apply (domain_type& x, range_type& b, [[maybe_unused]] double reduction, InverseOperatorResult& res) override
462 {
463 apply(x,b,res);
464 }
465
466 /**
467 * @brief additional apply method with c-arrays in analogy to superlu
468 * @param x solution array
469 * @param b rhs array
470 *
471 * NOTE If the user hands over a pure pointer, we assume that they know what they are doing, hence no copy to flat structures
472 */
473 void apply(T* x, T* b)
474 {
475 double UMF_Apply_Info[UMFPACK_INFO];
476 Caller::solve(UMFPACK_A,
477 umfpackMatrix_.getColStart(),
478 umfpackMatrix_.getRowIndex(),
479 umfpackMatrix_.getValues(),
480 x,
481 b,
482 UMF_Numeric,
483 UMF_Control,
484 UMF_Apply_Info);
485 printOnApply(UMF_Apply_Info);
486 }
487
488 /** @brief Set UMFPack-specific options
489 *
490 * This method allows to set various options that control the UMFPack solver.
491 * More specifically, it allows to set values in the UMF_Control array.
492 * Please see the UMFPack documentation for a list of possible options and values.
493 *
494 * \param option Entry in the UMF_Control array, e.g., UMFPACK_IRSTEP
495 * \param value Corresponding value
496 *
497 * \throws RangeError If nonexisting option was requested
498 */
499 void setOption(unsigned int option, double value)
500 {
501 if (option >= UMFPACK_CONTROL)
502 DUNE_THROW(RangeError, "Requested non-existing UMFPack option");
503
504 UMF_Control[option] = value;
505 }
506
507 /** @brief saves a decomposition to a file
508 * @param file the filename to save to
509 */
510 void saveDecomposition(const char* file)
511 {
512 int errcode = Caller::save_numeric(UMF_Numeric, const_cast<char*>(file));
513 if (errcode != UMFPACK_OK)
514 DUNE_THROW(Dune::Exception,"IO ERROR while trying to save UMFPack decomposition");
515 }
516
517 /** @brief Initialize data from given matrix.
518 *
519 * \tparam BitVector a compatible bitvector to the domain_type/range_type.
520 * Defaults to NoBitVector for backwards compatibility
521 *
522 * A positive bit indices that the corresponding matrix row/column is excluded from the
523 * UMFPACK decomposition.
524 * WARNING This is an opposite behavior of the previous implementation in `setSubMatrix`.
525 */
526 template<class BitVector = Impl::NoBitVector>
527 void setMatrix(const Matrix& matrix, const BitVector& bitVector = {})
528 {
529 if ((umfpackMatrix_.N() + umfpackMatrix_.M() > 0) || matrixIsLoaded_)
530 free();
531 if (matrix.N() == 0 or matrix.M() == 0)
532 return;
533
534 if (umfpackMatrix_.N() + umfpackMatrix_.M() + umfpackMatrix_.nonzeroes() != 0)
535 umfpackMatrix_.free();
536
537 constexpr bool useBitVector = not std::is_same_v<BitVector,Impl::NoBitVector>;
538
539 // use a dynamic flat vector for the bitset
540 std::vector<bool> flatBitVector;
541 // and a mapping from the compressed indices
542 std::vector<size_type> subIndices;
543
544 [[maybe_unused]] int numberOfIgnoredDofs = 0;
545 int nonZeros = 0;
546
547 if constexpr ( useBitVector )
548 {
549 auto flatSize = flatVectorForEach(bitVector, [](auto&&, auto&&){});
550 flatBitVector.resize(flatSize);
551
552 flatVectorForEach(bitVector, [&](auto&& entry, auto&& offset)
553 {
554 flatBitVector[ offset ] = entry;
555 if ( entry )
556 {
557 numberOfIgnoredDofs++;
558 }
559 });
560 }
561
562 // compute the flat dimension and the number of nonzeros of the matrix
563 auto [flatRows,flatCols] = flatMatrixForEach( matrix, [&](auto&& /*entry*/, auto&& row, auto&& col){
564 // do not count ignored entries
565 if constexpr ( useBitVector )
566 if ( flatBitVector[row] or flatBitVector[col] )
567 return;
568
569 nonZeros++;
570 });
571
572 if constexpr ( useBitVector )
573 {
574 // use the original flatRows!
575 subIndices.resize(flatRows,std::numeric_limits<std::size_t>::max());
576
577 size_type subIndexCounter = 0;
578 for ( size_type i=0; i<size_type(flatRows); i++ )
579 if ( not flatBitVector[ i ] )
580 subIndices[ i ] = subIndexCounter++;
581
582 // update the original matrix size
583 flatRows -= numberOfIgnoredDofs;
584 flatCols -= numberOfIgnoredDofs;
585 }
586
587
588 umfpackMatrix_.setSize(flatRows,flatCols);
589 umfpackMatrix_.Nnz_ = nonZeros;
590
591 // prepare the arrays
592 umfpackMatrix_.colstart = new size_type[flatCols+1];
593 umfpackMatrix_.rowindex = new size_type[nonZeros];
594 umfpackMatrix_.values = new T[nonZeros];
595
596 for ( size_type i=0; i<size_type(flatCols+1); i++ )
597 {
598 umfpackMatrix_.colstart[i] = 0;
599 }
600
601 // at first, we need to compute the column start indices
602 // therefore, we count all entries in each column and in the end we accumulate everything
603 flatMatrixForEach(matrix, [&](auto&& /*entry*/, auto&& flatRowIndex, auto&& flatColIndex)
604 {
605 // do nothing if entry is excluded
606 if constexpr ( useBitVector )
607 if ( flatBitVector[flatRowIndex] or flatBitVector[flatColIndex] )
608 return;
609
610 // pick compressed or uncompressed index
611 // compiler will hopefully do some constexpr optimization here
612 auto colIdx = useBitVector ? subIndices[flatColIndex] : flatColIndex;
613
614 umfpackMatrix_.colstart[colIdx+1]++;
615 });
616
617 // now accumulate
618 for ( size_type i=0; i<(size_type)flatCols; i++ )
619 {
620 umfpackMatrix_.colstart[i+1] += umfpackMatrix_.colstart[i];
621 }
622
623 // we need a compressed position counter in each column
624 std::vector<size_type> colPosition(flatCols,0);
625
626 // now we can set the entries: the procedure below works with both row- or column major index ordering
627 flatMatrixForEach(matrix, [&](auto&& entry, auto&& flatRowIndex, auto&& flatColIndex)
628 {
629 // do nothing if entry is excluded
630 if constexpr ( useBitVector )
631 if ( flatBitVector[flatRowIndex] or flatBitVector[flatColIndex] )
632 return;
633
634 // pick compressed or uncompressed index
635 // compiler will hopefully do some constexpr optimization here
636 auto rowIdx = useBitVector ? subIndices[flatRowIndex] : flatRowIndex;
637 auto colIdx = useBitVector ? subIndices[flatColIndex] : flatColIndex;
638
639 // the start index of each column is already fixed
640 auto colStart = umfpackMatrix_.colstart[colIdx];
641 // get the current number of picked elements in this column
642 auto colPos = colPosition[colIdx];
643 // assign the corresponding row index and the value of this element
644 umfpackMatrix_.rowindex[ colStart + colPos ] = rowIdx;
645 umfpackMatrix_.values[ colStart + colPos ] = entry;
646 // increase the number of picked elements in this column
647 colPosition[colIdx]++;
648 });
649
650 decompose();
651 }
652
653 // Keep legacy version using a set of scalar indices
654 // The new version using a bitVector type for marking the active matrix indices is
655 // directly given in `setMatrix` with an additional BitVector argument.
656 // The new version is more flexible and allows, e.g., marking single components of a matrix block.
657 void setSubMatrix(const Matrix& _mat, const std::set<typename Matrix::size_type>& rowIndexSet)
658 {
659 if ((umfpackMatrix_.N() + umfpackMatrix_.M() > 0) || matrixIsLoaded_)
660 free();
661
662 if (umfpackMatrix_.N() + umfpackMatrix_.M() + umfpackMatrix_.nonzeroes() != 0)
663 umfpackMatrix_.free();
664
665 umfpackMatrix_.setSize(rowIndexSet.size()*MatrixDimension<Matrix>::rowdim(_mat) / _mat.N(),
666 rowIndexSet.size()*MatrixDimension<Matrix>::coldim(_mat) / _mat.M());
667 ISTL::Impl::BCCSMatrixInitializer<Matrix, SuiteSparse_long> initializer(umfpackMatrix_);
668
669 copyToBCCSMatrix(initializer, ISTL::Impl::MatrixRowSubset<Matrix,std::set<typename Matrix::size_type> >(_mat,rowIndexSet));
670
671 decompose();
672 }
673
674 /** @brief sets the verbosity level for the UMFPack solver
675 * @param v verbosity level
676 * The following levels are implemented:
677 * 0 - only error messages
678 * 1 - a bit of statistics on decomposition and solution
679 * 2 - lots of statistics on decomposition and solution
680 */
681 void setVerbosity(int v)
682 {
683 verbosity_ = v;
684 // set the verbosity level in UMFPack
685 if (verbosity_ == 0)
686 UMF_Control[UMFPACK_PRL] = 1;
687 if (verbosity_ == 1)
688 UMF_Control[UMFPACK_PRL] = 2;
689 if (verbosity_ == 2)
690 UMF_Control[UMFPACK_PRL] = 4;
691 }
692
693 /**
694 * @brief Return the matrix factorization.
695 * @warning It is up to the user to keep consistency.
696 */
697 void* getFactorization()
698 {
699 return UMF_Numeric;
700 }
701
702 /**
703 * @brief Return the column compress matrix from UMFPack.
704 * @warning It is up to the user to keep consistency.
705 */
706 UMFPackMatrix& getInternalMatrix()
707 {
708 return umfpackMatrix_;
709 }
710
711 /**
712 * @brief free allocated space.
713 * @warning later calling apply will result in an error.
714 */
715 void free()
716 {
717 if (!matrixIsLoaded_)
718 {
719 Caller::free_symbolic(&UMF_Symbolic);
720 umfpackMatrix_.free();
721 }
722 Caller::free_numeric(&UMF_Numeric);
723 matrixIsLoaded_ = false;
724 }
725
726 const char* name() { return "UMFPACK"; }
727
728 private:
729 typedef typename Dune::UMFPackMethodChooser<T> Caller;
730
731 template<class Mat,class X, class TM, class TD, class T1>
732 friend class SeqOverlappingSchwarz;
733 friend struct SeqOverlappingSchwarzAssemblerHelper<UMFPack<Matrix>,true>;
734
735 /** @brief computes the LU Decomposition */
736 void decompose()
737 {
738 double UMF_Decomposition_Info[UMFPACK_INFO];
739 Caller::symbolic(static_cast<SuiteSparse_long>(umfpackMatrix_.N()),
740 static_cast<SuiteSparse_long>(umfpackMatrix_.N()),
741 umfpackMatrix_.getColStart(),
742 umfpackMatrix_.getRowIndex(),
743 reinterpret_cast<double*>(umfpackMatrix_.getValues()),
744 &UMF_Symbolic,
745 UMF_Control,
746 UMF_Decomposition_Info);
747 Caller::numeric(umfpackMatrix_.getColStart(),
748 umfpackMatrix_.getRowIndex(),
749 reinterpret_cast<double*>(umfpackMatrix_.getValues()),
750 UMF_Symbolic,
751 &UMF_Numeric,
752 UMF_Control,
753 UMF_Decomposition_Info);
754 Caller::report_status(UMF_Control,UMF_Decomposition_Info[UMFPACK_STATUS]);
755 if (verbosity_ == 1)
756 {
757 std::cout << "[UMFPack Decomposition]" << std::endl;
758 std::cout << "Wallclock Time taken: " << UMF_Decomposition_Info[UMFPACK_NUMERIC_WALLTIME] << " (CPU Time: " << UMF_Decomposition_Info[UMFPACK_NUMERIC_TIME] << ")" << std::endl;
759 std::cout << "Flops taken: " << UMF_Decomposition_Info[UMFPACK_FLOPS] << std::endl;
760 std::cout << "Peak Memory Usage: " << UMF_Decomposition_Info[UMFPACK_PEAK_MEMORY]*UMF_Decomposition_Info[UMFPACK_SIZE_OF_UNIT] << " bytes" << std::endl;
761 std::cout << "Condition number estimate: " << 1./UMF_Decomposition_Info[UMFPACK_RCOND] << std::endl;
762 std::cout << "Numbers of non-zeroes in decomposition: L: " << UMF_Decomposition_Info[UMFPACK_LNZ] << " U: " << UMF_Decomposition_Info[UMFPACK_UNZ] << std::endl;
763 }
764 if (verbosity_ == 2)
765 {
766 Caller::report_info(UMF_Control,UMF_Decomposition_Info);
767 }
768 }
769
770 void printOnApply(double* UMF_Info)
771 {
772 Caller::report_status(UMF_Control,UMF_Info[UMFPACK_STATUS]);
773 if (verbosity_ > 0)
774 {
775 std::cout << "[UMFPack Solve]" << std::endl;
776 std::cout << "Wallclock Time: " << UMF_Info[UMFPACK_SOLVE_WALLTIME] << " (CPU Time: " << UMF_Info[UMFPACK_SOLVE_TIME] << ")" << std::endl;
777 std::cout << "Flops Taken: " << UMF_Info[UMFPACK_SOLVE_FLOPS] << std::endl;
778 std::cout << "Iterative Refinement steps taken: " << UMF_Info[UMFPACK_IR_TAKEN] << std::endl;
779 std::cout << "Error Estimate: " << UMF_Info[UMFPACK_OMEGA1] << " resp. " << UMF_Info[UMFPACK_OMEGA2] << std::endl;
780 }
781 }
782
783 UMFPackMatrix umfpackMatrix_;
784 bool matrixIsLoaded_;
785 int verbosity_;
786 void *UMF_Symbolic;
787 void *UMF_Numeric;
788 double UMF_Control[UMFPACK_CONTROL];
789 };
790
791 template<typename M>
792 struct IsDirectSolver<UMFPack<M>>
793 {
794 enum { value=true};
795 };
796
797 template<typename T, typename A>
798 struct StoresColumnCompressed<UMFPack<BCRSMatrix<T,A> > >
799 {
800 enum { value = true };
801 };
802
803 namespace UMFPackImpl {
804 template<class OpTraits, class=void> struct isValidBlock : std::false_type{};
805 template<class OpTraits> struct isValidBlock<OpTraits,
806 std::enable_if_t<
807 std::is_same_v<Impl::UMFPackDomainType<typename OpTraits::matrix_type>, typename OpTraits::domain_type>
808 && std::is_same_v<Impl::UMFPackRangeType<typename OpTraits::matrix_type>, typename OpTraits::range_type>
809 && std::is_same_v<typename FieldTraits<typename OpTraits::domain_type::field_type>::real_type, double>
810 && std::is_same_v<typename FieldTraits<typename OpTraits::range_type::field_type>::real_type, double>
811 >> : std::true_type {};
812 }
813 DUNE_REGISTER_SOLVER("umfpack",
814 [](auto opTraits, const auto& op, const Dune::ParameterTree& config)
815 -> std::shared_ptr<typename decltype(opTraits)::solver_type>
816 {
817 using OpTraits = decltype(opTraits);
818 // works only for sequential operators
819 if constexpr (OpTraits::isParallel){
820 if(opTraits.getCommOrThrow(op).communicator().size() > 1)
821 DUNE_THROW(Dune::InvalidStateException, "UMFPack works only for sequential operators.");
822 }
823 if constexpr (OpTraits::isAssembled){
824 using M = typename OpTraits::matrix_type;
825 // check if UMFPack<M>* is convertible to
826 // InverseOperator*. This checks compatibility of the
827 // domain and range types
828 if constexpr (UMFPackImpl::isValidBlock<OpTraits>::value) {
829 const auto& A = opTraits.getAssembledOpOrThrow(op);
830 const M& mat = A->getmat();
831 int verbose = config.get("verbose", 0);
832 return std::make_shared<Dune::UMFPack<M>>(mat,verbose);
833 }
834 }
835 DUNE_THROW(UnsupportedType,
836 "Unsupported Type in UMFPack (only double and std::complex<double> supported)");
837 return nullptr;
838 });
839 } // end namespace Dune
840
841 #endif // HAVE_SUITESPARSE_UMFPACK
842
843 #endif //DUNE_ISTL_UMFPACK_HH