KASKADE 7 development version
Loading...
Searching...
No Matches
multiGridStacks.hh
Go to the documentation of this file.
1/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2/* */
3/* This file is part of the library KASKADE 7 */
4/* https://www.zib.de/research/projects/kaskade7-finite-element-toolbox */
5/* */
6/* Copyright (C) 2002-2012 Zuse Institute Berlin */
7/* */
8/* KASKADE 7 is distributed under the terms of the ZIB Academic License. */
9/* see $KASKADE/academic.txt */
10/* */
11/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12
17
18#ifndef MULTIGRIDSTACKS_HH
19#define MULTIGRIDSTACKS_HH
20
21#include <memory> // std::unique_ptr
22#include <vector>
23#include <map>
24#include <time.h>
25#include <math.h>
26#include <fstream>
27
28#include <iostream> // std::cout
29using std::cout;
30
31
32#include "dune/grid/common/grid.hh"
33#include "dune/grid/common/entitypointer.hh"
34#include "dune/grid/common/entity.hh"
35#include "dune/grid/io/file/dgfparser/dgfparser.hh"
36#include "dune/istl/matrix.hh"
37#include "dune/istl/bcrsmatrix.hh"
38#include "dune/common/fmatrix.hh"
39#include "dune/common/iteratorfacades.hh"
40#include "dune/istl/matrixindexset.hh"
41
42#include "dune/istl/preconditioners.hh"
43#include "dune/istl/solvers.hh"
44
45// #include "fem/barycentric.hh"
46#include "fem/fixdune.hh"
47#include "fem/mllgeometry.hh"
48#include "fem/fetransfer.hh"
49#include "linalg/conjugation.hh"
50#include "linalg/triplet.hh"
51
71
75
76//--------------------------------------------------------------------------------------------------------------------------
77
78
89template < class Grd >
91{
92 typedef typename Grd::LevelGridView::IndexSet::IndexType IndexType;
93 typedef typename std::pair<IndexType,float> FatherIndexValue;
94 typedef typename std::vector<FatherIndexValue> FatherSimplexPairs;
95
96 private:
97 void findParents( const Grd& grd, int levelNr );
98 public:
99 std::vector< std::vector<FatherSimplexPairs> > levelParentsVector;
100 std::vector< std::vector<int> > levelDisappear;
101
102 ParentalNodes( Grd const& grd ): levelParentsVector(grd.maxLevel()), levelDisappear(grd.maxLevel())
103 {
104 for(int levelNr=1; levelNr<=grd.maxLevel(); levelNr++)
105 findParents(grd,levelNr);
106 }
107};
108
109template < class Grd >
110void ParentalNodes<Grd>::findParents( const Grd& grd, int levelNr )
111{
112 // First we iterate through all elements in
113 // the current level. In each element we iterate through each corner node. First we check if we
114 // visited it before (vector "processed"). If not we collect the barycentric coordinates in
115 // the father element and the corresponding level indices of the father corner vertex in the
116 // level above ( using vector<pair<int index,double barycentricCoordinate> > >, each vector
117 // consisting of maximal four pairs ). We also collect the nodes, which disappear from one to
118 // another level, we need them (!) to build up consistent prolongations.
119
120 typedef typename Grd::template Codim<0>::LevelIterator ElementLevelIterator;
121 typedef typename Grd::LevelGridView::IndexSet::IndexType IndexType;
122
123 std::vector<FatherSimplexPairs> levelParents;
124 levelParents.resize( grd.size(levelNr,Grd::dimension) );
125
126 // helpvector to avoid multiple processing of identical vertices
127 std::vector<bool> processed(grd.size(Grd::dimension),false);
128
129 // disappearance monitor: necessary to keep track of disappearing nodes
130 std::vector<bool> disappears( grd.size(levelNr-1,Grd::dimension) , true );
131
132 typename Grd::LevelGridView::IndexSet const& indexSet = grd.levelGridView(levelNr).indexSet() ;
133 typename Grd::LevelGridView::IndexSet const& fatherIndexSet = grd.levelGridView(levelNr-1).indexSet();
134
135 // iterate through all cells on current level
136 ElementLevelIterator itEnd = grd.levelGridView(levelNr).template end<0>() ;
137 for (ElementLevelIterator it = grd.levelGridView(levelNr).template begin<0>() ; it != itEnd; ++it)
138 {
139 // for storing the father level indices of the father's corner points
140 std::vector<IndexType> fatherIndices;
141
142 // VertexPointer to father Corners
143 typename Grd::template Codim<0>::Entity itFather = (*it).father();
144
145 for(int i=0 ; i<=Grd::dimension ; i++ )
146 {
147 fatherIndices.push_back( fatherIndexSet.subIndex(itFather, i, Grd::dimension) );
148 // corners of the father cell won't disappear on coarser level
149 disappears[ indexSet.subIndex( itFather,i,Grd::dimension ) ] = false;
150 }
151
152 // now regard corners of subentity
153 for( int i=0 ; i<=Grd::dimension ; i++ )
154 {
155 IndexType idx_child = indexSet.subIndex(*it, i, Grd::dimension);
156 if (!processed[idx_child])
157 {
158 processed[idx_child] = true;
159
160 std::vector<float> relativeCoord;
161 relativeCoord.push_back(1);
162 for( int component = 0 ; component < Grd::dimension ; component++ )
163 {
164 relativeCoord.push_back( it->geometryInFather().corner(i)[component] );
165 relativeCoord.front() -= relativeCoord.back();
166 }
167
168 for( int component = 0 ; component <= Grd::dimension ; component++ )
169 {
170 FatherIndexValue couple;
171 couple.first = fatherIndices[component];
172 couple.second = relativeCoord[component];
173 levelParents[idx_child].push_back(couple);
174 }
175
176 // TODO: instead use barycentric() from fem/barycentric.hh, something like this:
177 // Dune::FieldVector<typename Grd::ctype,Grd::dimension+1> relativeCoord
178 // = barycentric(it->geometryInFather().corner(i));
179 // ...for() {...
180 // couple.second = relativeCoord[(component+1)%(Grd::dimension+1)];
181 // ... }
182 //
183 // somehow barycentric coordinates are in different order than mine
184
185 }
186 }
187 }
188
189 // store which nodes will not turn up on the coarser level
190 for (int k = 0 ; k < disappears.size(); k++ )
191 if(disappears[k])
192 levelDisappear[levelNr-1].push_back(k);
193
194 // move data to the global store.
195 levelParentsVector[levelNr-1].swap(levelParents);
196}
197
198//--------------------------------------------------------------------------------------------------------------------------
199
224
225// example usage: ProlongationStack<Grid> prolstack( gridManager.grid() );
226
227// creates Vector prolStack of prolongationmatrices
228template < class Grd >
230{
232
233 public:
234 std::vector<Dune::BCRSMatrix<M> > prolStack;
235 ProlongationStack( const Grd& grd );
236};
237
238
239template < class Grd >
241{
242 int maxiLevel = grd.maxLevel();
243 // creates levelParentsVector
244 ParentalNodes<Grd> parentalNodes( grd );
245
246 std::vector<std::vector<int> > disappear(parentalNodes.levelDisappear);
247
248 int disappearSumBefore = 0;
249 int disappearSumAfter = 0;
250
251 for(int levelNr = 1 ; levelNr <= maxiLevel ; levelNr++)
252 {
253 disappearSumBefore = disappearSumAfter;
254 disappearSumAfter += disappear[levelNr-1].size();
255
256 int prolCols = grd.size( levelNr-1 , Grd::dimension ) + disappearSumBefore ;
257 int prolRows = grd.size( levelNr , Grd::dimension ) + disappearSumAfter ;
258
259 // In order to create a BCRS Prolongation matrix we first compute an upper bound for the
260 // number of nonzeros. The nodes on lower levels just retain their values and are not
261 // interpolated, hence there is exactly one nonzero entry in the row.
262 // Each child node's value is determined by the dim+1 values of its father simplex's corners, such that
263 // each row has at most dim+1 nonzeros. Most refinement schemes lead to even sparser prolongation matrices,
264 // as not all father's corners contribute. We start with the worst case here.
265 int nz = disappearSumAfter + grd.size(levelNr,Grd::dimension)*(Grd::dimension+1);
266 Dune::BCRSMatrix<M> prolMatrix(prolRows,prolCols,nz,Dune::BCRSMatrix<M>::row_wise);
267
268 // Now we create the sparsity pattern. Here we can be more precise and allocate only those entries
269 // which are actually nonzero. Remember that "very close to zero" barycentric coordinates have been
270 // set to exactly zero.
272
273 for (Iter row=prolMatrix.createbegin(); row!=prolMatrix.createend(); ++row)
274 {
275 if (row.index() < disappearSumBefore)
276 row.insert( row.index() );
277 else if (row.index() >= disappearSumBefore && row.index() < disappearSumAfter )
278 row.insert( disappearSumBefore + disappear[levelNr-1][ row.index() - disappearSumBefore ] );
279 else
280 for( int k = 0 ; k <= Grd::dimension ; k++ )
281 if (parentalNodes.levelParentsVector[levelNr-1][row.index()-disappearSumAfter][k].second > 0)
282 row.insert( parentalNodes.levelParentsVector[levelNr-1][row.index()-disappearSumAfter][k].first + disappearSumBefore );
283 }
284
285 // now enter the values
286 for(int row = 0 ; row < disappearSumBefore ; row++)
287 prolMatrix[row][row] = 1;
288 for(int indx = 0 ; indx < disappear[levelNr-1].size(); indx++)
289 prolMatrix[ disappearSumBefore + indx ][ disappear[levelNr-1][indx] + disappearSumBefore ] = 1;
290 for(int row = disappearSumAfter ; row < prolRows ; row++)
291 {
292 for( int k = 0 ; k <= Grd::dimension ; k++ )
293 if (parentalNodes.levelParentsVector[levelNr-1][row-disappearSumAfter /*row.index()*/][k].second > 0)
294 {
295 prolMatrix[row][ parentalNodes.levelParentsVector[levelNr-1][row-disappearSumAfter][k].first + disappearSumBefore ]
296 = parentalNodes.levelParentsVector[levelNr-1][row-disappearSumAfter][k].second;
297 }
298 }
299
300 prolStack.push_back( prolMatrix );
301 }
302}
303
304// ------------------------------------------------------------------------------------------------------
305
317
318// example usage: ProlongationStack<Grid> prolStack( gridManager.grid() ); MlStack<Grid> myStack( prolStack , bcrsMatrix );
319
320// creates vector levelMatrixStack of level stiffness matrices
321template < class Grd >
323{
325 public:
326 // sets the member levelMatrixStack, a vector of level stiffness matrices
327 MlStack( ProlongationStack<Grd> const& ps , Dune::BCRSMatrix<M> const& bcrsA , bool onlyLowerTriangle = false);
328 std::vector<Dune::BCRSMatrix<M> > levelMatrixStack;
329};
330
331
332template < class Grd >
333MlStack<Grd>::MlStack(ProlongationStack<Grd> const& ps , Dune::BCRSMatrix<M> const& bcrsA , bool onlyLowerTriangle)
334{
335 // number of prolongations ( = # gridlevels - 1 )
336 int prols = ps.prolStack.size();
337 // sets the first entry of levelMatrixStack to A (stiffness matrix on leaflevel)
338 levelMatrixStack.push_back(bcrsA);
339
340 for(int i = 0 ; i < prols ; i++)
341 {
342 // format needed for toolbox conjugation.hh --> C=C+P^T*A*P
343 std::unique_ptr<Dune::MatrixIndexSet> C = conjugationPattern<double,M>( ps.prolStack[prols-1-i] , levelMatrixStack[ i ] , onlyLowerTriangle);
345 // exportIdx from Dune::MatrixIndexSet
346 C->exportIdx(Cnew);
347 // initialize Cnew
348 Cnew *= 0.0;
349 // now Cnew = Cnew + P^T * A * P , where P and A are level corresponding
350 // prolongation- and stiffness matrices
351 conjugation( Cnew , ps.prolStack[prols-1-i] , levelMatrixStack[ i ] , onlyLowerTriangle );
352 // append new stiffness matrix
353 levelMatrixStack.push_back( Cnew );
354 }
355}
356
357// ------------------------------------------------------------------------------------------------------
358
372
373template < class Grd , class domain_type >
375{
378 typedef Dune::SeqJac<Dune::BCRSMatrix<M>,CoeffVector,CoeffVector> JacobiSmoother;
379 private:
380 int mNumOfLevels;
381 const ProlongationStack<Grd> &mProlongations;
382 const MlStack<Grd> &mLevelMatrices;
383 double mJacRelaxFactor, mMgIter, mMgSmoothings, mMaxTol, mTimeDirectSolve , mExactSolEnergyNorm ;
384 public:
385 MultigridSolver( const ProlongationStack<Grd>& prolongations,
386 const MlStack<Grd>& levelMatrices,
387 double relax,
388 double mgIter,
389 double mgSmoothings,
390 double maxTol );
391 void mgSolve( domain_type& solution , domain_type& rightHand );
392 private:
393 void mgSolveRecursive( CoeffVector& solution , CoeffVector& rightHand , int Level );
394 void jacobiSmooth( CoeffVector& solution , CoeffVector& rightHand , int Level );
395};
396
397// constructor
398template < class Grd , class domain_type >
400 const MlStack<Grd>& levelMatrices,
401 double relax,
402 double mgIter,
403 double mgSmoothings,
404 double maxTol
405 ): mProlongations( prolongations ),
406 mLevelMatrices( levelMatrices )
407{
408 mNumOfLevels = levelMatrices.levelMatrixStack.size();
409 mJacRelaxFactor = relax;
410 mMgIter = mgIter;
411 mMgSmoothings = mgSmoothings;
412 mMaxTol = maxTol;
413}
414
415//member mgSolve()
416template < class Grd , class domain_type >
417void MultigridSolver<Grd,domain_type>::mgSolve( domain_type& domain_type_solution , domain_type& domain_type_rightHand )
418{
419 int Level = mNumOfLevels - 1;
420 double relDefect;
421
422 // references Dune::BlockVector
423 CoeffVector &solution = boost::fusion::at_c<0>(domain_type_solution.data);
424 CoeffVector &rightHand = boost::fusion::at_c<0>(domain_type_rightHand.data);
425
426 for(int i=0;i<mMgIter;i++)
427 {
428 mgSolveRecursive( solution , rightHand , Level );
429 // calculate relative Defect
430 CoeffVector defect(rightHand);
431 mLevelMatrices.levelMatrixStack.front().mmv( solution , defect );
432 relDefect = defect.two_norm()/rightHand.two_norm();
433 if( relDefect < mMaxTol)
434 {
435 cout << "MG converged: " << i << " iterations. rel.Defect = "<< relDefect<< "\n";
436 break;
437 }
438 else if( i==mMgIter-1 )
439 cout << "MG not converged: " << mMgIter << " iterations. rel. Defect = "<< relDefect<< '\n';
440 }
441}
442
443//member mgSolveRecursive()
444template < class Grd, class domain_type >
445void MultigridSolver<Grd,domain_type>::mgSolveRecursive( CoeffVector& solution , CoeffVector& rightHand , int Level )
446{
447 if(Level==0)
448 {
449 // direct solve on Level 0
450 Dune::MatrixAdapter<Dune::BCRSMatrix<M>, CoeffVector, CoeffVector> matrixAdapter( mLevelMatrices.levelMatrixStack.back() );
451 TrivialPreconditioner<CoeffVector> trivialPrecond;
452 Dune::InverseOperatorResult resultInfo;
453 CoeffVector rhsDummy(rightHand);
454 Dune::CGSolver<CoeffVector> cg( matrixAdapter , trivialPrecond , 1.0e-14 , 1000 , 0 );
455 cg.apply( solution , rhsDummy , resultInfo );
456 mTimeDirectSolve += resultInfo.elapsed;
457
458 }
459 else
460 {
461 // pre-smoothing
462 jacobiSmooth( solution , rightHand , Level );
463 CoeffVector levelRightHand( mProlongations.prolStack[Level-1].M() ), tmpRhs(rightHand);
464 mLevelMatrices.levelMatrixStack[mNumOfLevels-Level-1].mmv( solution , tmpRhs );// mmv(const X &x, Y &y) ... y -= A x
465 // restriction residual:
466 mProlongations.prolStack[Level-1].mtv( tmpRhs , levelRightHand );// mtv(const X &x, Y &y) ... y = A^T x
467 // initialize level-error
468 CoeffVector levelError(levelRightHand);
469 levelError *= 0;
470 mgSolveRecursive( levelError , levelRightHand , Level - 1 );
471 // prolongate correction
472 mProlongations.prolStack[Level-1].umv( levelError , solution );// umv(const X &x, Y &y) ... y += A x
473 // post-smoothing
474 jacobiSmooth( solution , rightHand , Level );
475 }
476}
477
478
479// member jacobiSmooth()
480template < class Grd ,class domain_type>
481void MultigridSolver<Grd,domain_type>::jacobiSmooth( CoeffVector& solution , CoeffVector& rightHand , int Level )
482{
483 JacobiSmoother jacobi( mLevelMatrices.levelMatrixStack[ mNumOfLevels-Level-1 ] , mMgSmoothings , mJacRelaxFactor );
484 CoeffVector rhsDummy(rightHand);
485 jacobi.pre( solution , rhsDummy );
486 jacobi.apply( solution , rhsDummy );
487 jacobi.post( solution );
488}
489
490// ------------------------------------------------------------------------------------------------------
491
492// for output in console
494{
495 for(int i=0;i<bcrsMatrix.N();i++)
496 {
497 for(int k =0;k<bcrsMatrix.M();k++)
498 {
499 if(bcrsMatrix.exists(i,k)) cout << bcrsMatrix[i][k] << " ";
500 else cout << "0 ";
501 }
502 cout << '\n';
503 }
504 cout<<'\n';
505}
506
507// ------------------------------------------------------------------------------------------------------
508
509
511{
513 Avec_=0;
514 matrix_.mv(vec_,Avec_);// mv (const X &x, Y &y) ... y = A x
515 return sqrt(Avec_*vec_);
516}
517
518#endif
std::size_t IndexType
Definition alphabet.hh:27
MlStack(ProlongationStack< Grd > const &ps, Dune::BCRSMatrix< M > const &bcrsA, bool onlyLowerTriangle=false)
std::vector< Dune::BCRSMatrix< M > > levelMatrixStack
void mgSolve(domain_type &solution, domain_type &rightHand)
MultigridSolver(const ProlongationStack< Grd > &prolongations, const MlStack< Grd > &levelMatrices, double relax, double mgIter, double mgSmoothings, double maxTol)
Finds the parent nodes and their interpolation weight for each node in the grid. usage eg....
std::vector< std::vector< FatherSimplexPairs > > levelParentsVector
std::vector< std::vector< int > > levelDisappear
ParentalNodes(Grd const &grd)
std::vector< Dune::BCRSMatrix< M > > prolStack
ProlongationStack(const Grd &grd)
Tools for transfer of data between grids.
This file contains various utility functions that augment the basic functionality of Dune.
Class for transformations between ancestors and their children.
void bcrsPrint(const Dune::BCRSMatrix< Dune::FieldMatrix< double, 1, 1 > > &bcrsMatrix)
double energyNorm(const Dune::BCRSMatrix< Dune::FieldMatrix< double, 1, 1 > > &matrix_, const Dune::BlockVector< Dune::FieldVector< double, 1 > > &vec_)
auto & component(LinearProductSpace< Scalar, Sequence > &x)