ParallelOverlappingILU0_impl.hpp
Go to the documentation of this file.
1/*
2 Copyright 2015, 2022 Dr. Blatt - HPC-Simulation-Software & Services
3 Copyright 2015 Statoil AS
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
22
23#include <dune/common/version.hh>
24
25#include <dune/istl/ilu.hh>
26#include <dune/istl/owneroverlapcopy.hh>
27
28#include <opm/common/ErrorMacros.hpp>
29#include <opm/common/TimingMacros.hpp>
30
32#include <opm/simulators/linalg/matrixblock.hh>
33
34namespace Opm
35{
36namespace detail
37{
38
40template<class M>
41void ghost_last_bilu0_decomposition (M& A, std::size_t interiorSize)
42{
43 // iterator types
44 using rowiterator = typename M::RowIterator;
45 using coliterator = typename M::ColIterator;
46 using block = typename M::block_type;
47
48 // implement left looking variant with stored inverse
49 for (rowiterator i = A.begin(); i.index() < interiorSize; ++i)
50 {
51 // coliterator is diagonal after the following loop
52 coliterator endij=(*i).end(); // end of row i
53 coliterator ij;
54
55 // eliminate entries left of diagonal; store L factor
56 for (ij=(*i).begin(); ij.index()<i.index(); ++ij)
57 {
58 // find A_jj which eliminates A_ij
59 coliterator jj = A[ij.index()].find(ij.index());
60
61 // compute L_ij = A_jj^-1 * A_ij
62 (*ij).rightmultiply(*jj);
63
64 // modify row
65 coliterator endjk=A[ij.index()].end(); // end of row j
66 coliterator jk=jj; ++jk;
67 coliterator ik=ij; ++ik;
68 while (ik!=endij && jk!=endjk)
69 if (ik.index()==jk.index())
70 {
71 block B(*jk);
72 B.leftmultiply(*ij);
73 *ik -= B;
74 ++ik; ++jk;
75 }
76 else
77 {
78 if (ik.index()<jk.index())
79 ++ik;
80 else
81 ++jk;
82 }
83 }
84
85 // invert pivot and store it in A
86 if (ij.index()!=i.index())
87 DUNE_THROW(Dune::ISTLError,"diagonal entry missing");
88 try {
89 (*ij).invert(); // compute inverse of diagonal block
90 }
91 catch (Dune::FMatrixError & e) {
92 DUNE_THROW(Dune::ISTLError,"ILU failed to invert matrix block");
93 }
94 }
95}
96
98template<class M, class CRS, class InvVector>
99void convertToCRS(const M& A, CRS& lower, CRS& upper, InvVector& inv)
100{
101 OPM_TIMEBLOCK(convertToCRS);
102 // No need to do anything for 0 rows. Return to prevent indexing a
103 // a zero sized array.
104 if ( A.N() == 0 )
105 {
106 return;
107 }
108
109 using size_type = typename M :: size_type;
110
111 lower.clear();
112 upper.clear();
113 inv.clear();
114 lower.resize( A.N() );
115 upper.resize( A.N() );
116 inv.resize( A.N() );
117
118 // Count the lower and upper matrix entries.
119 size_type numLower = 0;
120 size_type numUpper = 0;
121 const auto endi = A.end();
122 for (auto i = A.begin(); i != endi; ++i) {
123 const size_type iIndex = i.index();
124 size_type numLowerRow = 0;
125 for (auto j = (*i).begin(); j.index() < iIndex; ++j) {
126 ++numLowerRow;
127 }
128 numLower += numLowerRow;
129 numUpper += (*i).size() - numLowerRow - 1;
130 }
131 assert(numLower + numUpper + A.N() == A.nonzeroes());
132
133 lower.reserveAdditional( numLower );
134
135 // implement left looking variant with stored inverse
136 size_type row = 0;
137 size_type colcount = 0;
138 lower.rows_[ 0 ] = colcount;
139 for (auto i=A.begin(); i!=endi; ++i, ++row)
140 {
141 const size_type iIndex = i.index();
142
143 // eliminate entries left of diagonal; store L factor
144 for (auto j=(*i).begin(); j.index() < iIndex; ++j )
145 {
146 lower.push_back( (*j), j.index() );
147 ++colcount;
148 }
149 lower.rows_[ iIndex+1 ] = colcount;
150 }
151
152 assert(colcount == numLower);
153
154 const auto rendi = A.beforeBegin();
155 row = 0;
156 colcount = 0;
157 upper.rows_[ 0 ] = colcount ;
158
159 upper.reserveAdditional( numUpper );
160
161 // NOTE: upper and inv store entries in reverse order, reverse here
162 // relative to ILU
163 for (auto i=A.beforeEnd(); i!=rendi; --i, ++ row )
164 {
165 const size_type iIndex = i.index();
166
167 // store in reverse row order
168 // eliminate entries left of diagonal; store L factor
169 for (auto j=(*i).beforeEnd(); j.index()>=iIndex; --j )
170 {
171 const size_type jIndex = j.index();
172 if( j.index() == iIndex )
173 {
174 inv[ row ] = (*j);
175 break;
176 }
177 else if ( j.index() >= i.index() )
178 {
179 upper.push_back( (*j), jIndex );
180 ++colcount ;
181 }
182 }
183 upper.rows_[ row+1 ] = colcount;
184 }
185 assert(colcount == numUpper);
186}
187
188} // end namespace detail
189
190
191template<class Matrix, class Domain, class Range, class ParallelInfoT>
192Dune::SolverCategory::Category
194{
195 return std::is_same_v<ParallelInfoT, Dune::Amg::SequentialInformation> ?
196 Dune::SolverCategory::sequential : Dune::SolverCategory::overlapping;
197}
198
199template<class Matrix, class Domain, class Range, class ParallelInfoT>
201ParallelOverlappingILU0(const Matrix& A,
202 const int n, const field_type w,
203 MILU_VARIANT milu, bool redblack,
204 bool reorder_sphere)
205 : lower_(),
206 upper_(),
207 inv_(),
208 comm_(nullptr), w_(w),
209 relaxation_( std::abs( w - 1.0 ) > 1e-15 ),
210 A_(&reinterpret_cast<const Matrix&>(A)), iluIteration_(n),
211 milu_(milu), redBlack_(redblack), reorderSphere_(reorder_sphere)
212{
213 interiorSize_ = A.N();
214 // BlockMatrix is a Subclass of FieldMatrix that just adds
215 // methods. Therefore this cast should be safe.
216 update();
217}
218
219template<class Matrix, class Domain, class Range, class ParallelInfoT>
221ParallelOverlappingILU0(const Matrix& A,
222 const ParallelInfo& comm, const int n, const field_type w,
223 MILU_VARIANT milu, bool redblack,
224 bool reorder_sphere)
225 : lower_(),
226 upper_(),
227 inv_(),
228 comm_(&comm), w_(w),
229 relaxation_( std::abs( w - 1.0 ) > 1e-15 ),
230 A_(&reinterpret_cast<const Matrix&>(A)), iluIteration_(n),
231 milu_(milu), redBlack_(redblack), reorderSphere_(reorder_sphere)
232{
233 interiorSize_ = A.N();
234 // BlockMatrix is a Subclass of FieldMatrix that just adds
235 // methods. Therefore this cast should be safe.
236 update();
237}
238
239template<class Matrix, class Domain, class Range, class ParallelInfoT>
241ParallelOverlappingILU0(const Matrix& A,
242 const field_type w, MILU_VARIANT milu, bool redblack,
243 bool reorder_sphere)
244 : ParallelOverlappingILU0( A, 0, w, milu, redblack, reorder_sphere )
245{}
246
247template<class Matrix, class Domain, class Range, class ParallelInfoT>
249ParallelOverlappingILU0(const Matrix& A,
250 const ParallelInfo& comm, const field_type w,
251 MILU_VARIANT milu, bool redblack,
252 bool reorder_sphere)
253 : lower_(),
254 upper_(),
255 inv_(),
256 comm_(&comm), w_(w),
257 relaxation_( std::abs( w - 1.0 ) > 1e-15 ),
258 A_(&reinterpret_cast<const Matrix&>(A)), iluIteration_(0),
259 milu_(milu), redBlack_(redblack), reorderSphere_(reorder_sphere)
260{
261 interiorSize_ = A.N();
262 // BlockMatrix is a Subclass of FieldMatrix that just adds
263 // methods. Therefore this cast should be safe.
264 update();
265}
266
267template<class Matrix, class Domain, class Range, class ParallelInfoT>
269ParallelOverlappingILU0(const Matrix& A,
270 const ParallelInfo& comm,
271 const field_type w, MILU_VARIANT milu,
272 size_type interiorSize, bool redblack,
273 bool reorder_sphere)
274 : lower_(),
275 upper_(),
276 inv_(),
277 comm_(&comm), w_(w),
278 relaxation_( std::abs( w - 1.0 ) > 1e-15 ),
279 interiorSize_(interiorSize),
280 A_(&reinterpret_cast<const Matrix&>(A)), iluIteration_(0),
281 milu_(milu), redBlack_(redblack), reorderSphere_(reorder_sphere)
282{
283 // BlockMatrix is a Subclass of FieldMatrix that just adds
284 // methods. Therefore this cast should be safe.
285 update( );
286}
287
288template<class Matrix, class Domain, class Range, class ParallelInfoT>
290apply (Domain& v, const Range& d)
291{
292 OPM_TIMEBLOCK(apply);
293 Range& md = reorderD(d);
294 Domain& mv = reorderV(v);
295
296 // iterator types
297 using dblock = typename Range ::block_type;
298 using vblock = typename Domain::block_type;
299
300 const size_type iEnd = lower_.rows();
301 const size_type lastRow = iEnd - 1;
302 size_type upperLoopStart = iEnd - interiorSize_;
303 size_type lowerLoopEnd = interiorSize_;
304 if (iEnd != upper_.rows())
305 {
306 OPM_THROW(std::logic_error,"ILU: number of lower and upper rows must be the same");
307 }
308
309 // lower triangular solve
310 for (size_type i = 0; i < lowerLoopEnd; ++i)
311 {
312 dblock rhs( md[ i ] );
313 const size_type rowI = lower_.rows_[ i ];
314 const size_type rowINext = lower_.rows_[ i+1 ];
315
316 for (size_type col = rowI; col < rowINext; ++col)
317 {
318 lower_.values_[ col ].mmv( mv[ lower_.cols_[ col ] ], rhs );
319 }
320
321 mv[ i ] = rhs; // Lii = I
322 }
323
324 for (size_type i = upperLoopStart; i < iEnd; ++i)
325 {
326 vblock& vBlock = mv[ lastRow - i ];
327 vblock rhs ( vBlock );
328 const size_type rowI = upper_.rows_[ i ];
329 const size_type rowINext = upper_.rows_[ i+1 ];
330
331 for (size_type col = rowI; col < rowINext; ++col)
332 {
333 upper_.values_[ col ].mmv( mv[ upper_.cols_[ col ] ], rhs );
334 }
335
336 // apply inverse and store result
337 inv_[ i ].mv( rhs, vBlock);
338 }
339
340 copyOwnerToAll( mv );
341
342 if( relaxation_ ) {
343 mv *= w_;
344 }
345 reorderBack(mv, v);
346}
347
348template<class Matrix, class Domain, class Range, class ParallelInfoT>
349template<class V>
351copyOwnerToAll(V& v) const
352{
353 if( comm_ ) {
354 comm_->copyOwnerToAll(v, v);
355 }
356}
357
358template<class Matrix, class Domain, class Range, class ParallelInfoT>
360update()
361{
362 OPM_TIMEBLOCK(update);
363 // (For older DUNE versions the communicator might be
364 // invalid if redistribution in AMG happened on the coarset level.
365 // Therefore we check for nonzero size
366 if (comm_ && comm_->communicator().size() <= 0)
367 {
368 if (A_->N() > 0)
369 {
370 OPM_THROW(std::logic_error, "Expected a matrix with zero rows for an invalid communicator.");
371 }
372 else
373 {
374 // simply set the communicator to null
375 comm_ = nullptr;
376 }
377 }
378
379 int ilu_setup_successful = 1;
380 std::string message;
381 const int rank = comm_ ? comm_->communicator().rank() : 0;
382
383 if (redBlack_)
384 {
385 using Graph = Dune::Amg::MatrixGraph<const Matrix>;
386 Graph graph(*A_);
387 auto colorsTuple = colorVerticesWelshPowell(graph);
388 const auto& colors = std::get<0>(colorsTuple);
389 const auto& verticesPerColor = std::get<2>(colorsTuple);
390 auto noColors = std::get<1>(colorsTuple);
391 if ( reorderSphere_ )
392 {
393 ordering_ = reorderVerticesSpheres(colors, noColors, verticesPerColor,
394 graph, 0);
395 }
396 else
397 {
398 ordering_ = reorderVerticesPreserving(colors, noColors, verticesPerColor,
399 graph);
400 }
401 }
402
403 std::vector<std::size_t> inverseOrdering(ordering_.size());
404 std::size_t index = 0;
405 for (const auto newIndex : ordering_)
406 {
407 inverseOrdering[newIndex] = index++;
408 }
409
410 try
411 {
412 OPM_TIMEBLOCK(iluDecomposition);
413 if (iluIteration_ == 0) {
414 // create ILU-0 decomposition
415 if (ordering_.empty())
416 {
417 if (ILU_) {
418 OPM_TIMEBLOCK(iluDecompositionMakeMatrix);
419 // The ILU_ matrix is already a copy with the same
420 // sparse structure as A_, but the values of A_ may
421 // have changed, so we must copy all elements.
422 for (std::size_t row = 0; row < A_->N(); ++row) {
423 const auto& Arow = (*A_)[row];
424 auto& ILUrow = (*ILU_)[row];
425 auto Ait = Arow.begin();
426 auto Iit = ILUrow.begin();
427 for (; Ait != Arow.end(); ++Ait, ++Iit) {
428 *Iit = *Ait;
429 }
430 }
431 } else {
432 // First call, must duplicate matrix.
433 ILU_ = std::make_unique<Matrix>(*A_);
434 }
435 }
436 else
437 {
438 ILU_ = std::make_unique<Matrix>(A_->N(), A_->M(),
439 A_->nonzeroes(), Matrix::row_wise);
440 auto& newA = *ILU_;
441 // Create sparsity pattern
442 for (auto iter = newA.createbegin(), iend = newA.createend(); iter != iend; ++iter)
443 {
444 const auto& row = (*A_)[inverseOrdering[iter.index()]];
445 for (auto col = row.begin(), cend = row.end(); col != cend; ++col)
446 {
447 iter.insert(ordering_[col.index()]);
448 }
449 }
450 // Copy values
451 for (auto iter = A_->begin(), iend = A_->end(); iter != iend; ++iter)
452 {
453 auto& newRow = newA[ordering_[iter.index()]];
454 for (auto col = iter->begin(), cend = iter->end(); col != cend; ++col)
455 {
456 newRow[ordering_[col.index()]] = *col;
457 }
458 }
459 }
460
461 switch (milu_)
462 {
465 break;
467 detail::milu0_decomposition ( *ILU_, detail::identityFunctor<typename Matrix::field_type>,
468 detail::signFunctor<typename Matrix::field_type> );
469 break;
471 detail::milu0_decomposition ( *ILU_, detail::absFunctor<typename Matrix::field_type>,
472 detail::signFunctor<typename Matrix::field_type> );
473 break;
475 detail::milu0_decomposition ( *ILU_, detail::identityFunctor<typename Matrix::field_type>,
476 detail::isPositiveFunctor<typename Matrix::field_type> );
477 break;
478 default:
479 if (interiorSize_ == A_->N())
480#if DUNE_VERSION_LT(DUNE_GRID, 2, 8)
481 bilu0_decomposition( *ILU_ );
482#else
483 Dune::ILU::blockILU0Decomposition( *ILU_ );
484#endif
485 else
486 detail::ghost_last_bilu0_decomposition(*ILU_, interiorSize_);
487 break;
488 }
489 }
490 else {
491 // create ILU-n decomposition
492 ILU_ = std::make_unique<Matrix>(A_->N(), A_->M(), Matrix::row_wise);
493 std::unique_ptr<detail::Reorderer> reorderer, inverseReorderer;
494 if (ordering_.empty())
495 {
496 reorderer.reset(new detail::NoReorderer());
497 inverseReorderer.reset(new detail::NoReorderer());
498 }
499 else
500 {
501 reorderer.reset(new detail::RealReorderer(ordering_));
502 inverseReorderer.reset(new detail::RealReorderer(inverseOrdering));
503 }
504
505 milun_decomposition( *A_, iluIteration_, milu_, *ILU_, *reorderer, *inverseReorderer );
506 }
507 }
508 catch (const Dune::MatrixBlockError& error)
509 {
510 message = error.what();
511 std::cerr << "Exception occurred on process " << rank << " during " <<
512 "setup of ILU0 preconditioner with message: "
513 << message<<std::endl;
514 ilu_setup_successful = 0;
515 }
516
517 // Check whether there was a problem on some process
518 const bool parallel_failure = comm_ && comm_->communicator().min(ilu_setup_successful) == 0;
519 const bool local_failure = ilu_setup_successful == 0;
520 if (local_failure || parallel_failure)
521 {
522 throw Dune::MatrixBlockError();
523 }
524
525 // store ILU in simple CRS format
526 detail::convertToCRS(*ILU_, lower_, upper_, inv_);
527}
528
529template<class Matrix, class Domain, class Range, class ParallelInfoT>
531reorderD(const Range& d)
532{
533 if (ordering_.empty())
534 {
535 // As d is non-const in the apply method of the
536 // solver casting away constness in this particular
537 // setting is not undefined. It is ugly though but due
538 // to the preconditioner interface of dune-istl.
539 return const_cast<Range&>(d);
540 }
541 else
542 {
543 reorderedD_.resize(d.size());
544 std::size_t i = 0;
545 for (const auto index : ordering_)
546 {
547 reorderedD_[index] = d[i++];
548 }
549 return reorderedD_;
550 }
551}
552
553template<class Matrix, class Domain, class Range, class ParallelInfoT>
555reorderV(Domain& v)
556{
557 if (ordering_.empty())
558 {
559 return v;
560 }
561 else
562 {
563 reorderedV_.resize(v.size());
564 std::size_t i = 0;
565 for (const auto index : ordering_)
566 {
567 reorderedV_[index] = v[i++];
568 }
569 return reorderedV_;
570 }
571}
572
573template<class Matrix, class Domain, class Range, class ParallelInfoT>
575reorderBack(const Range& reorderedV, Range& v)
576{
577 if (!ordering_.empty())
578 {
579 std::size_t i = 0;
580 for (const auto index : ordering_)
581 {
582 v[i++] = reorderedV[index];
583 }
584 }
585}
586
587} // end namespace Opm
A two-step version of an overlapping Schwarz preconditioner using one step ILU0 as.
Definition: ParallelOverlappingILU0.hpp:131
ParallelOverlappingILU0(const Matrix &A, const int n, const field_type w, MILU_VARIANT milu, bool redblack=false, bool reorder_sphere=true)
Constructor.
Definition: ParallelOverlappingILU0_impl.hpp:201
Domain & reorderV(Domain &v)
Reorder V if needed and return a reference to it.
Definition: ParallelOverlappingILU0_impl.hpp:555
size_type interiorSize_
Definition: ParallelOverlappingILU0.hpp:346
void reorderBack(const Range &reorderedV, Range &v)
Definition: ParallelOverlappingILU0_impl.hpp:575
Range & reorderD(const Range &d)
Reorder D if needed and return a reference to it.
Definition: ParallelOverlappingILU0_impl.hpp:531
void copyOwnerToAll(V &v) const
Definition: ParallelOverlappingILU0_impl.hpp:351
Dune::SolverCategory::Category category() const override
Definition: ParallelOverlappingILU0_impl.hpp:193
void update() override
Definition: ParallelOverlappingILU0_impl.hpp:360
void apply(Domain &v, const Range &d) override
Apply the preconditoner.
Definition: ParallelOverlappingILU0_impl.hpp:290
typename matrix_type::size_type size_type
Definition: ParallelOverlappingILU0.hpp:145
typename Domain::field_type field_type
The field type of the preconditioner.
Definition: ParallelOverlappingILU0.hpp:142
void milu0_decomposition(M &A, FieldFunct< M > absFunctor=signFunctor< typename M::field_type >, FieldFunct< M > signFunctor=oneFunctor< typename M::field_type >, std::vector< typename M::block_type > *diagonal=nullptr)
void convertToCRS(const M &A, CRS &lower, CRS &upper, InvVector &inv)
compute ILU decomposition of A. A is overwritten by its decomposition
Definition: ParallelOverlappingILU0_impl.hpp:99
void milun_decomposition(const M &A, int n, MILU_VARIANT milu, M &ILU, Reorderer &ordering, Reorderer &inverseOrdering)
void ghost_last_bilu0_decomposition(M &A, std::size_t interiorSize)
Compute Blocked ILU0 decomposition, when we know junk ghost rows are located at the end of A.
Definition: ParallelOverlappingILU0_impl.hpp:41
Definition: BlackoilPhases.hpp:27
MILU_VARIANT
Definition: MILU.hpp:34
@ MILU_1
sum(dropped entries)
@ MILU_2
sum(dropped entries)
@ MILU_3
sum(|dropped entries|)
@ MILU_4
sum(dropped entries)
std::vector< std::size_t > reorderVerticesPreserving(const std::vector< int > &colors, int noColors, const std::vector< std::size_t > &verticesPerColor, const Graph &graph)
! Reorder colored graph preserving order of vertices with the same color.
Definition: GraphColoring.hpp:169
std::vector< std::size_t > reorderVerticesSpheres(const std::vector< int > &colors, int noColors, const std::vector< std::size_t > &verticesPerColor, const Graph &graph, typename Graph::VertexDescriptor root)
! Reorder Vetrices in spheres
Definition: GraphColoring.hpp:189
std::tuple< std::vector< int >, int, std::vector< std::size_t > > colorVerticesWelshPowell(const Graph &graph)
Color the vertices of graph.
Definition: GraphColoring.hpp:113
Definition: MILU.hpp:76
Definition: MILU.hpp:84