ProblemStat.inc.hpp 11.4 KB
Newer Older
1
2
3
#pragma once


4
5
6
7
8
9
#include <dune/istl/solvers.hh>
#include <dune/istl/preconditioners.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>

#include "AdaptInfo.hpp"
#include "Loops.hpp"
10
11
12
13
#include "Timer.hpp"

namespace AMDiS
{
14
15
16
17
    template <class Param>
    void ProblemStat<Param>::initialize(Flag initFlag,
					ProblemStat* adoptProblem,
					Flag adoptFlag) 
18
19
20
    {
	// === create meshes ===
	if (mesh) {
21
	    AMDIS_WARNING("mesh already created");
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
	}
	else {
	    if (initFlag.isSet(CREATE_MESH) ||
		(!adoptFlag.isSet(INIT_MESH) &&
		(initFlag.isSet(INIT_SYSTEM) || initFlag.isSet(INIT_FE_SPACE)))) {
		createMesh();
	    }

	    if (adoptProblem &&
		(adoptFlag.isSet(INIT_MESH) ||
		adoptFlag.isSet(INIT_SYSTEM) ||
		adoptFlag.isSet(INIT_FE_SPACE))) {
		mesh = adoptProblem->getMesh();
	    }
	    
	    componentMeshes.resize(nComponents, mesh.get());
	}

	if (!mesh) {
41
	    AMDIS_WARNING("no mesh created");
42
43
44
45
46
	}
	
	
	// === create fespace ===
	if (feSpaces) {
47
	    AMDIS_WARNING("feSpaces already created");
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
	}
	else {
	    if (initFlag.isSet(INIT_FE_SPACE) ||
		(initFlag.isSet(INIT_SYSTEM) && !adoptFlag.isSet(INIT_FE_SPACE))) {
		createFeSpaces();
	    }

	    if (adoptProblem &&
		(adoptFlag.isSet(INIT_FE_SPACE) || adoptFlag.isSet(INIT_SYSTEM))) {
		feSpaces = adoptProblem->getFeSpaces();
	    }
	}
	
	
	int globalRefinements = 0;
	Parameters::get(meshName + "->global refinements", globalRefinements);
	mesh->globalRefine(globalRefinements);
65
66
67
	
	solution->compress();
	rhs->compress();
68
69
70
    }
  
  
71
72
73
74
75
    template <class Param>
    void ProblemStat<Param>::addMatrixOperator(OperatorType& op, 
					       int i, int j,
					       double* factor, 
					       double* estFactor)
76
77
78
79
80
81
82
83
    {
	// TODO: currently the factors are ignored
	assert( factor == NULL && estFactor == NULL );
	
	matrixOperators[std::make_pair(i,j)].push_back(std::make_shared<OperatorType>(op));
    }

    
84
85
86
87
88
    template <class Param>
    void ProblemStat<Param>::addVectorOperator(OperatorType& op, 
					       int i,
					       double* factor, 
					       double* estFactor)
89
90
91
92
93
94
95
96
97
98
    {
	// TODO: currently the factors are ignored
	assert( factor == NULL && estFactor == NULL );
	
	vectorOperators[i].push_back(std::make_shared<OperatorType>(op));
    }

  
  
  /// Adds a Dirichlet boundary condition
99
  template <class Param>
100
    template <class Predicate, class Values>
101
102
103
  void ProblemStat<Param>::addDirichletBC(Predicate const& predicate, 
					  int row, int col, 
					  Values const& values)
104
105
106
107
108
109
110
  {
    static_assert(Dune::Functions::Concept::isCallable<Predicate, WorldVector>(), 
      "Function passed to addDirichletBC for predicate does not model the Callable<WorldVector> concept");
    
    static_assert(Dune::Functions::Concept::isCallable<Values, WorldVector>(), 
      "Function passed to addDirichletBC for values does not model the Callable<WorldVector> concept");

111
112
    AMDIS_TEST_EXIT(row >= 0 && row < nComponents, "row number out of range: " << row);
    AMDIS_TEST_EXIT(col >= 0 && col < nComponents, "col number out of range: " << col);
113
    
114
//     boundaryConditionSet = true;
115
116
117
118
119
120
121
122

    using BcType = DirichletBC<WorldVector>;
    std::shared_ptr<BcType> dirichlet = std::make_shared<BcType>(predicate, values);
      
    dirichletBc[std::make_pair(row, col)].push_back( dirichlet );
  }
  
  
123
124
125
126
  template <class Param>
  void ProblemStat<Param>::solve(AdaptInfo& adaptInfo, 
				 bool createMatrixData, 
				 bool storeMatrixData)
127
128
129
130
131
132
133
134
135
  {
//     if (!solver) {
//       WARNING("no solver\n");
//       return;
//     }

    Timer t;
    
    // NOTE: just to show the priciple, with initial solution 0
136
137
138
139
140
//     For<0, nComponents>::loop([this](auto const _i) {
// 	solution->getVector(_i) = 0.0;
//     });
    
    using VectorType = std::tuple_element_t<0, typename SystemVectorType::BaseVectors>;
141
142
    
    // Technicality : turn the matrix into a linear operator
143
    Dune::MatrixAdapter<DOFMatrix, VectorType, VectorType> op(systemMatrix[0][0]);
144
145

    // Sequential incomplete LU decomposition as the preconditioner
146
    Dune::SeqILU0<DOFMatrix, VectorType, VectorType> ilu0(systemMatrix[0][0], 1.0);
147
148

    // Preconditioned conjugate−gradient solver
149
    Dune::CGSolver<VectorType> cg(op, ilu0, 1.e-4, 500, 2);
150
151

    // storing some statistics
152
    Dune::InverseOperatorResult statistics;
153
154

    // solve the linear system
155
156
    constexpr index_<0> _0;
    cg.apply(solution->getVector(_0), rhs->getVector(_0), statistics);
157
    
158
    AMDIS_MSG("solution of discrete system needed " << t.elapsed() << " seconds");
159

160
161
162
163
    adaptInfo.setSolverIterations(statistics.iterations);
//     adaptInfo.setMaxSolverIterations(solver->getMaxIterations());
//     adaptInfo.setSolverTolerance(solver->getTolerance());
    adaptInfo.setSolverResidual(statistics.reduction);
164
165
166
  }
  
  
167
168
169
  template <class Param>
  void ProblemStat<Param>::buildAfterCoarsen(AdaptInfo& /*adaptInfo*/, Flag flag,
					     bool asmMatrix, bool asmVector)
170
171
  {
    Timer t;
172
173
    solution->compress();
      
174
175
176
177

    For<0, nComponents>::loop([this, asmMatrix, asmVector](auto const _r) 
    {
      if (asmVector) {
178
179
	rhs->compress(_r);
        rhs->getVector(_r) = 0.0;
180
181
      }

182
      For<0, nComponents>::loop([this, asmMatrix, asmVector, _r](auto const _c) 
183
      {
184
185
	auto const& rowFeSpace = this->getFeSpace(_r);
        auto const& colFeSpace = this->getFeSpace(_c);
186
	
187
188
	int r = int(_r), c = int(_c);
	auto row_col = std::make_pair(r, c);
189
190
	
        // The DOFMatrix which should be assembled
191
        DOFMatrix& matrix = systemMatrix[_r][_c];
192
193
194
	  
	if (asmMatrix) {
	  // TODO: calc occupationPattern only once for each feSpace
195
196
	  Dune::MatrixIndexSet occupationPattern;
	  this->getOccupationPattern(rowFeSpace, colFeSpace, occupationPattern);
197
198
199
200
201
202
	  occupationPattern.exportIdx(matrix);

	  // TODO: only set to zero if not keep the matrix
	  matrix = 0.0;

	  // init boundary condition
203
204
205
206
207
208
209
210
	  for (auto bc_list : dirichletBc) {
	    std::tie(r, c) = bc_list.first;
	    if (r == int(_r)) {
		for (auto bc : bc_list.second)
		    bc->init(c == int(_c), 
			     rowFeSpace, colFeSpace, &matrix, 
			     &rhs->getVector(_r), 
			     &solution->getVector(_c));
211
212
213
	    }
	  }
	  
214
215
	  this->assemble(row_col, rowFeSpace, colFeSpace, &matrix,
		  (_r == _c && asmVector ? &rhs->getVector(_r) : NULL));
216
217

	  // finish boundary condition
218
219
220
221
222
223
224
225
	  for (auto bc_list : dirichletBc) {
	    std::tie(r, c) = bc_list.first;
	    if (r == int(_r)) {
		for (auto bc : bc_list.second)
		    bc->finish(c == int(_c), 
			       rowFeSpace, colFeSpace, &matrix, 
			       &rhs->getVector(_r), 
			       &solution->getVector(_c));
226
227
228
	    }
	  }
	}
229
230
      });
    });
231
    
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    AMDIS_MSG("buildAfterCoarsen needed " << t.elapsed() << " seconds");
  }
  

  template <class Param>
  void ProblemStat<Param>::writeFiles(AdaptInfo& adaptInfo, double time)
  {
    Timer t;
    
    Dune::VTKWriter<MeshView> vtkWriter(*meshView);
    For<0, nComponents>::loop([this, &vtkWriter](const auto _i) {
	vtkWriter.addVertexData(solution->getVector(_i), componentNames[_i]);
    });
    
    std::string filename = "";
    Parameters::get(name + "->output->filename", filename);
    if (time >= 0.0)
	filename += std::to_string(time);
    
    vtkWriter.write(filename);


    AMDIS_MSG("writeFiles needed " << t.elapsed() << " seconds");
255
256
257
258
259
  }
  
  
  
  // Get the occupation pattern
260
  template <class Param>
261
    template <class RowFeSpace, class ColFeSpace>
262
263
264
  void ProblemStat<Param>::getOccupationPattern(const RowFeSpace& rowFeSpace, 
						const ColFeSpace& colFeSpace, 
						Dune::MatrixIndexSet& nb)
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
  {
      nb.resize(rowFeSpace.size(), colFeSpace.size());

      // A loop over all elements of the grid
      auto rowView = rowFeSpace.localView();
      auto rowIndexSet = rowFeSpace.localIndexSet();
      
      auto colView = colFeSpace.localView();
      auto colIndexSet = colFeSpace.localIndexSet();

      for (const auto& element : elements(*meshView)) {
	  rowView.bind(element);
	  rowIndexSet.bind(rowView); // TODO: can this be moved out of the loop?
	  
	  colView.bind(element);
	  colIndexSet.bind(colView); // TODO: can this be moved out of the loop?
	  
	  for (size_t i = 0; i < rowIndexSet.size(); ++i) {
	      // The global index of the i-th vertex of the element
	      auto row = rowIndexSet.index(i);
	      for (size_t j = 0; j < colIndexSet.size(); ++j) {
		  // The global index of the j-th vertex of the element
		  auto col = colIndexSet.index(j);
		  nb.add(row, col);
	      }
	  }
      }
  }


295
296
297
298
299
300
301
  template <class Param>
    template <class RowFeSpace, class ColFeSpace, class Vector>
  void ProblemStat<Param>::assemble(std::pair<int, int> row_col,
				    const RowFeSpace& rowFeSpace, 
				    const ColFeSpace& colFeSpace, 
				    DOFMatrix* matrix,
				    Vector* rhs)
302
  {
303
304
305
306
307
      for (auto op : matrixOperators[row_col])
	op->init(rowFeSpace, colFeSpace);
      for (auto op : vectorOperators[row_col.first])
	op->init(rowFeSpace, colFeSpace);
	      
308
309
310
311
312
313
      auto rowView = rowFeSpace.localView();
      auto rowIndexSet = rowFeSpace.localIndexSet();
      
      auto colView = colFeSpace.localView();
      auto colIndexSet = colFeSpace.localIndexSet();
      
314
      for (const auto& element : elements(*meshView)) {
315
316
317
318
319
320
	  rowView.bind(element);
	  rowIndexSet.bind(rowView);
	  
	  colView.bind(element);
	  colIndexSet.bind(colView);
	  
321
	  if (matrix) {	      
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
	      ElementMatrix elementMatrix;

	      // DOFMatrix::assemble {
	      bool add = getElementMatrix(rowView, colView, elementMatrix, matrixOperators[row_col]);

	      // DOFMatrix::addElementMatrix {
	      if (add) {
		  for (size_t i = 0; i < elementMatrix.N(); ++i) {
		      // The global index of the i−th vertex of the element
		      const auto row = rowIndexSet.index(i);
		      for (size_t j = 0; j < elementMatrix.M(); ++j) {
			  // The global index of the j−th vertex of the element
			  const auto col = colIndexSet.index(j);
			  (*matrix)[row][col] += elementMatrix[i][j];
		      }
		  }
	      }
	      // }
	      // }
	  }
	  
	  if (rhs) {
	      ElementVector elementVector;
	      
	      // DOFVectorBase<double>::assemble {
	      bool add = getElementVector(rowView, elementVector, vectorOperators[row_col.first]);
	      
	      // DOFVectorBase<T>::addElementVector {
	      if (add) {
		  for (size_t i = 0; i < elementVector.size(); ++i) {
		      // The global index of the i-th vertex
		      const auto row = rowIndexSet.index(i);
		      (*rhs)[row] += elementVector[i];
		  }
	      }
	      // }
	      // }
	  }
      }
  }
  
  
364
  template <class Param>
365
    template <class RowView, class ColView>
366
367
368
369
  bool ProblemStat<Param>::getElementMatrix(RowView const& rowView,
					    ColView const& colView,
					    ElementMatrix& elementMatrix,
					    std::list<std::shared_ptr<OperatorType>>& operators)
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
  {
    const auto& rowFE = rowView.tree().finiteElement();
    const auto& colFE = colView.tree().finiteElement();

    elementMatrix.setSize(rowFE.size(), colFE.size());
    elementMatrix = 0.0; // fills the entire matrix with zeroes

    for (auto op : operators)
      op->getElementMatrix(rowView, colView, elementMatrix);
    
    return !operators.empty();
  }
  
  
  
385
  template <class Param>
386
    template <class RowView>
387
388
389
  bool ProblemStat<Param>::getElementVector(RowView const& rowView,
					    ElementVector& elementVector,
					    std::list<std::shared_ptr<OperatorType>>& operators)
390
391
392
393
394
395
396
397
398
399
400
401
402
403
  {
    const auto& rowFE = rowView.tree().finiteElement();

    // Set all entries to zero
    elementVector.resize(rowFE.size());
    elementVector = 0.0;

    for (auto op : operators)
      op->getElementVector(rowView, elementVector);
    
    return !operators.empty();
  }

} // end namespace AMDiS