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

3
4
5
6
#include <map>
#include <string>
#include <utility>

7
#include <dune/common/hybridutilities.hh>
8
#include <dune/common/timer.hh>
9
#include <dune/functions/functionspacebases/subspacebasis.hh>
10
#include <dune/grid/common/capabilities.hh>
11
12
#include <dune/typetree/childextraction.hh>

13
#include <amdis/AdaptInfo.hpp>
14
#include <amdis/BackupRestore.hpp>
15
#include <amdis/Assembler.hpp>
16
#include <amdis/GridFunctionOperator.hpp>
Praetorius, Simon's avatar
Praetorius, Simon committed
17
#include <amdis/io/FileWriterCreator.hpp>
18
#include <amdis/linearalgebra/SymmetryStructure.hpp>
19

20
21
namespace AMDiS {

22
23
template <class Traits>
void ProblemStat<Traits>::initialize(
24
25
26
    Flag initFlag,
    Self* adoptProblem,
    Flag adoptFlag)
27
{
28
  // create grids
29
  if (grid_) {
30
    warning("grid already created");
31
32
33
34
35
  }
  else {
    if (initFlag.isSet(CREATE_MESH) ||
        (!adoptFlag.isSet(INIT_MESH) &&
        (initFlag.isSet(INIT_SYSTEM) || initFlag.isSet(INIT_FE_SPACE)))) {
36
      createGrid();
37
    }
38

39
40
41
42
    if (adoptProblem &&
        (adoptFlag.isSet(INIT_MESH) ||
        adoptFlag.isSet(INIT_SYSTEM) ||
        adoptFlag.isSet(INIT_FE_SPACE))) {
43
      adoptGrid(adoptProblem->grid_, adoptProblem->boundaryManager_);
44
    }
45
  }
46

47
  if (!grid_)
48
    warning("no grid created");
49

50
  // create fespace
51
  if (globalBasis_) {
52
    warning("globalBasis already created");
53
54
55
56
  }
  else {
    if (initFlag.isSet(INIT_FE_SPACE) ||
        (initFlag.isSet(INIT_SYSTEM) && !adoptFlag.isSet(INIT_FE_SPACE))) {
57
      createGlobalBasis();
58
    }
59

60
61
    if (adoptProblem &&
        (adoptFlag.isSet(INIT_FE_SPACE) || adoptFlag.isSet(INIT_SYSTEM))) {
Praetorius, Simon's avatar
Praetorius, Simon committed
62
      adoptGlobalBasis(adoptProblem->globalBasis_);
63
    }
64
  }
65

66
  if (!globalBasis_)
67
    warning("no globalBasis created\n");
68

69
70
71
  // create system
  if (initFlag.isSet(INIT_SYSTEM))
    createMatricesAndVectors();
72

73
  if (adoptProblem && adoptFlag.isSet(INIT_SYSTEM)) {
Praetorius, Simon's avatar
Praetorius, Simon committed
74
    systemMatrix_ = adoptProblem->systemMatrix_;
75
76
    solution_ = adoptProblem->solution_;
    rhs_ = adoptProblem->rhs_;
Praetorius, Simon's avatar
Praetorius, Simon committed
77
    estimates_ = adoptProblem->estimates_;
78
  }
79

80

81
  // create solver
82
  if (linearSolver_) {
83
84
85
86
87
    warning("solver already created\n");
  }
  else {
    if (initFlag.isSet(INIT_SOLVER))
      createSolver();
88

89
    if (adoptProblem && adoptFlag.isSet(INIT_SOLVER)) {
90
91
      test_exit(!linearSolver_, "solver already created\n");
      linearSolver_ = adoptProblem->linearSolver_;
92
    }
93
94
  }

95
  if (!linearSolver_) {
96
    warning("no solver created\n");
97
98
  }

99
100
101
102
103
  // create marker
    if (initFlag.isSet(INIT_MARKER))
      createMarker();

    if (adoptProblem && adoptFlag.isSet(INIT_MARKER))
104
      marker_ = adoptProblem->marker_;
105

106

107
108
109
  // create file writer
  if (initFlag.isSet(INIT_FILEWRITER))
    createFileWriter();
110

111
  solution_->resizeZero();
112
}
113

114

Praetorius, Simon's avatar
Praetorius, Simon committed
115
116
117
118
119
120
121
122
123
template <class Traits>
void ProblemStat<Traits>::
restore(Flag initFlag)
{
  std::string grid_filename = Parameters::get<std::string>(name_ + "->restore->grid").value();
  std::string solution_filename = Parameters::get<std::string>(name_ + "->restore->solution").value();
  test_exit(filesystem::exists(grid_filename), "Restore file '{}' not found.", grid_filename);
  test_exit(filesystem::exists(solution_filename), "Restore file '{}' not found.", solution_filename);

Praetorius, Simon's avatar
Praetorius, Simon committed
124
125
126
  // TODO(SP): implement BAckupRestore independent of wrapped grid
  using HostGrid = typename Grid::HostGrid;

Praetorius, Simon's avatar
Praetorius, Simon committed
127
  // restore grid from file
128
  if (Dune::Capabilities::hasBackupRestoreFacilities<HostGrid>::v)
Praetorius, Simon's avatar
Praetorius, Simon committed
129
    adoptGrid(std::shared_ptr<HostGrid>(Dune::BackupRestoreFacility<HostGrid>::restore(grid_filename)));
Praetorius, Simon's avatar
Praetorius, Simon committed
130
  else
Praetorius, Simon's avatar
Praetorius, Simon committed
131
    adoptGrid(std::shared_ptr<HostGrid>(BackupRestoreByGridFactory<HostGrid>::restore(grid_filename)));
Praetorius, Simon's avatar
Praetorius, Simon committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154

  // create fespace
  if (initFlag.isSet(INIT_FE_SPACE) || initFlag.isSet(INIT_SYSTEM))
    createGlobalBasis();

  // create system
  if (initFlag.isSet(INIT_SYSTEM))
    createMatricesAndVectors();

  // create solver
  if (linearSolver_)
    warning("solver already created\n");
  else if (initFlag.isSet(INIT_SOLVER))
    createSolver();

  // create marker
  if (initFlag.isSet(INIT_MARKER))
    createMarker();

  // create file writer
  if (initFlag.isSet(INIT_FILEWRITER))
    createFileWriter();

155
  solution_->resize(sizeInfo(*globalBasis_));
Praetorius, Simon's avatar
Praetorius, Simon committed
156
157
158
159
  solution_->restore(solution_filename);
}


Praetorius, Simon's avatar
Praetorius, Simon committed
160
161
162
163
template <class Traits>
void ProblemStat<Traits>::createGrid()
{
  Parameters::get(name_ + "->mesh", gridName_);
Praetorius, Simon's avatar
Praetorius, Simon committed
164
165

  MeshCreator<Grid> creator(gridName_);
166
  grid_ = creator.create();
167

168
  boundaryManager_ = std::make_shared<BoundaryManager<Grid>>(grid_);
169
170
  if (!creator.boundaryIds().empty())
    boundaryManager_->setBoundaryIds(creator.boundaryIds());
Praetorius, Simon's avatar
Praetorius, Simon committed
171

172
173
174
175
176
177
178
  info(3,"Create grid:");
  info(3,"#elements = {}"   , grid_->size(0));
  info(3,"#faces/edges = {}", grid_->size(1));
  info(3,"#vertices = {}"   , grid_->size(dim));
  info(3,"overlap-size = {}", grid_->leafGridView().overlapSize(0));
  info(3,"ghost-size = {}"  , grid_->leafGridView().ghostSize(0));
  info(3,"");
Praetorius, Simon's avatar
Praetorius, Simon committed
179
180
181
182
183
184
185
186
187
188
189
}


template <class T, class GV>
using HasCreate = decltype(T::create(std::declval<GV>()));


template <class Traits>
void ProblemStat<Traits>::createGlobalBasis()
{
  createGlobalBasisImpl(Dune::Std::is_detected<HasCreate,Traits,GridView>{});
190
  initGlobalBasis();
Praetorius, Simon's avatar
Praetorius, Simon committed
191
192
193
194
195
196
197
}


template <class Traits>
void ProblemStat<Traits>::createGlobalBasisImpl(std::true_type)
{
  assert( bool(grid_) );
198
  static_assert(std::is_same_v<GridView, typename Grid::LeafGridView>, "");
199
200
  auto basis = Traits::create(name_, grid_->leafGridView());
  globalBasis_ = std::make_shared<GlobalBasis>(std::move(basis));
Praetorius, Simon's avatar
Praetorius, Simon committed
201
202
203
204
205
206
207
208
209
210
211
}


template <class Traits>
void ProblemStat<Traits>::createGlobalBasisImpl(std::false_type)
{
  error_exit("Cannot create GlobalBasis from type. Pass a BasisCreator instead!");
}


template <class Traits>
212
void ProblemStat<Traits>::initGlobalBasis() {}
Praetorius, Simon's avatar
Praetorius, Simon committed
213
214
215
216
217


template <class Traits>
void ProblemStat<Traits>::createMatricesAndVectors()
{
218
  systemMatrix_ = std::make_shared<SystemMatrix>(globalBasis_, globalBasis_);
219
220
221
222
  std::string symmetryStr = "unknown";
  Parameters::get(name_ + "->symmetry", symmetryStr);
  systemMatrix_->setSymmetryStructure(symmetryStr);

Praetorius, Simon's avatar
Praetorius, Simon committed
223
  solution_ = std::make_shared<SolutionVector>(globalBasis_);
224
  rhs_ = std::make_shared<SystemVector>(globalBasis_);
225

Praetorius, Simon's avatar
Praetorius, Simon committed
226
  auto localView = globalBasis_->localView();
227
  for_each_node(localView.tree(), [&,this](auto&&, auto treePath) -> void
Praetorius, Simon's avatar
Praetorius, Simon committed
228
229
230
231
232
233
234
235
236
237
238
239
240
  {
    std::string i = to_string(treePath);
    estimates_[i].resize(globalBasis_->gridView().indexSet().size(0));
    for (std::size_t j = 0; j < estimates_[i].size(); j++)
      estimates_[i][j] = 0.0; // TODO: Remove when estimate() is implemented
  });
}


template <class Traits>
void ProblemStat<Traits>::createSolver()
{
  std::string solverName = "default";
241
  Parameters::get(name_ + "->solver", solverName);
Praetorius, Simon's avatar
Praetorius, Simon committed
242
243

  auto solverCreator
Praetorius, Simon's avatar
Praetorius, Simon committed
244
    = named(CreatorMap<LinearSolver>::getCreator(solverName, name_ + "->solver"));
Praetorius, Simon's avatar
Praetorius, Simon committed
245

246
  linearSolver_ = solverCreator->createWithString(name_ + "->solver");
Praetorius, Simon's avatar
Praetorius, Simon committed
247
248
249
}


250
251
252
template <class Traits>
void ProblemStat<Traits>::createMarker()
{
Praetorius, Simon's avatar
Praetorius, Simon committed
253
  marker_.clear();
254
  auto localView = globalBasis_->localView();
255
  for_each_node(localView.tree(), [&,this](auto&&, auto treePath) -> void
256
  {
257
    std::string componentName = name_ + "->marker[" + to_string(treePath) + "]";
258
259
260
261

    if (!Parameters::get<std::string>(componentName + "->strategy"))
      return;

262
    std::string tp = to_string(treePath);
Praetorius, Simon's avatar
Praetorius, Simon committed
263
264
    auto newMarker
      = EstimatorMarker<Grid>::createMarker(componentName, tp, estimates_[tp], grid_);
265
    assert(bool(newMarker));
266
    this->addMarker(std::move(newMarker));
267
268
269
270
  });
}


271
272
template <class Traits>
void ProblemStat<Traits>::createFileWriter()
273
{
Praetorius, Simon's avatar
Praetorius, Simon committed
274
  FileWriterCreator<SolutionVector> creator(solution_, boundaryManager_);
Praetorius, Simon's avatar
Praetorius, Simon committed
275

Praetorius, Simon's avatar
Praetorius, Simon committed
276
  filewriter_.clear();
277
  auto localView = globalBasis_->localView();
Praetorius, Simon's avatar
Praetorius, Simon committed
278
  for_each_node(localView.tree(), [&](auto const& /*node*/, auto treePath) -> void
279
  {
280
    std::string componentName = name_ + "->output[" + to_string(treePath) + "]";
Praetorius, Simon's avatar
Praetorius, Simon committed
281
282
283
284
285
286
287
    auto format = Parameters::get<std::vector<std::string>>(componentName + "->format");

    if (!format && to_string(treePath).empty()) {
      // alternative for root treepath
      componentName = name_ + "->output";
      format = Parameters::get<std::vector<std::string>>(componentName + "->format");
    }
288

Praetorius, Simon's avatar
Praetorius, Simon committed
289
    if (!format)
290
291
      return;

Praetorius, Simon's avatar
Praetorius, Simon committed
292
293
294
295
296
    for (std::string const& type : format.value()) {
      auto writer = creator.create(type, componentName, treePath);
      if (writer)
        filewriter_.push_back(std::move(writer));
    }
297
298
299
300
  });
}


301
// Adds a Dirichlet boundary condition
302
template <class Traits>
303
  template <class Predicate, class RowTreePath, class ColTreePath, class Values>
304
void ProblemStat<Traits>::
305
addDirichletBC(Predicate const& predicate, RowTreePath row, ColTreePath col, Values const& values)
306
307
{
  static_assert( Concepts::Functor<Predicate, bool(WorldVector)>,
308
    "Function passed to addDirichletBC for `predicate` does not model the Functor<bool(WorldVector)> concept");
309

310
311
312
  auto localView = globalBasis_->localView();
  auto i = child(localView.tree(), makeTreePath(row));
  auto j = child(localView.tree(), makeTreePath(col));
313
314
  auto rowBasis = Dune::Functions::subspaceBasis(*globalBasis_, makeTreePath(row));
  auto colBasis = Dune::Functions::subspaceBasis(*globalBasis_, makeTreePath(col));
315

316
  auto valueGridFct = makeGridFunction(values, this->gridView());
317

318
319
320
  auto bc = makeDirichletBC<SystemMatrix, SolutionVector, SystemVector>(
              std::move(rowBasis), std::move(colBasis), {predicate}, valueGridFct);
  boundaryConditions_[i][j].push_back(makeUniquePtr(std::move(bc)));
321
322
323
324
325
326
327
328
329
330
331
332
}


// Adds a Dirichlet boundary condition
template <class Traits>
  template <class RowTreePath, class ColTreePath, class Values>
void ProblemStat<Traits>::
addDirichletBC(BoundaryType id, RowTreePath row, ColTreePath col, Values const& values)
{
  auto localView = globalBasis_->localView();
  auto i = child(localView.tree(), makeTreePath(row));
  auto j = child(localView.tree(), makeTreePath(col));
333
334
  auto rowBasis = Dune::Functions::subspaceBasis(*globalBasis_, makeTreePath(row));
  auto colBasis = Dune::Functions::subspaceBasis(*globalBasis_, makeTreePath(col));
335

336
  auto valueGridFct = makeGridFunction(values, this->gridView());
337

338
339
340
  auto bc = makeDirichletBC<SystemMatrix, SolutionVector, SystemVector>(
              std::move(rowBasis), std::move(colBasis), {*boundaryManager_, id}, valueGridFct);
  boundaryConditions_[i][j].push_back(makeUniquePtr(std::move(bc)));
341
342
343
344
345
346
347
348
}


template <class Traits>
void ProblemStat<Traits>::
addPeriodicBC(BoundaryType id, WorldMatrix const& matrix, WorldVector const& vector)
{
  auto localView = globalBasis_->localView();
349
350
351
352
  auto basis = Dune::Functions::subspaceBasis(*globalBasis_, treepath());
  auto bc = makePeriodicBC<SystemMatrix, SolutionVector, SystemVector>(
              std::move(basis), {*boundaryManager_, id}, {matrix, vector});
  boundaryConditions_[localView.tree()][localView.tree()].push_back(makeUniquePtr(std::move(bc)));
353
}
354

355

356
357
template <class Traits>
void ProblemStat<Traits>::
358
solve(AdaptInfo& /*adaptInfo*/, bool createMatrixData, bool storeMatrixData)
359
{
360
  Dune::Timer t;
361

362
  SolverInfo solverInfo(name_ + "->solver");
363
364
365
  solverInfo.setCreateMatrixData(createMatrixData);
  solverInfo.setStoreMatrixData(storeMatrixData);

366
  solution_->resize();
Praetorius, Simon's avatar
Praetorius, Simon committed
367
  linearSolver_->solve(*systemMatrix_, *solution_, *rhs_, solverInfo);
368

Praetorius, Simon's avatar
Praetorius, Simon committed
369
  if (solverInfo.info() > 0) {
370
    msg("solution of discrete system needed {} seconds", t.elapsed());
371

Praetorius, Simon's avatar
Praetorius, Simon committed
372
373
    if (solverInfo.absResidual() >= 0.0) {
      if (solverInfo.relResidual() >= 0.0)
374
        msg("Residual norm: ||b-Ax|| = {}, ||b-Ax||/||b|| = {}",
Praetorius, Simon's avatar
Praetorius, Simon committed
375
          solverInfo.absResidual(), solverInfo.relResidual());
376
      else
Praetorius, Simon's avatar
Praetorius, Simon committed
377
        msg("Residual norm: ||b-Ax|| = {}", solverInfo.absResidual());
378
379
    }
  }
380

381
  test_exit(!solverInfo.doBreak() && !solverInfo.error(), "Could not solver the linear system!");
382
}
383

384

385
template <class Traits>
Praetorius, Simon's avatar
Praetorius, Simon committed
386
387
Flag ProblemStat<Traits>::
markElements(AdaptInfo& adaptInfo)
388
389
390
391
{
  Dune::Timer t;

  Flag markFlag = 0;
392
  for (auto& currentMarker : marker_)
393
    markFlag |= currentMarker.second->markGrid(adaptInfo);
394

395
  msg("markElements needed {} seconds", t.elapsed());
396
397
398
399
400

  return markFlag;
}


401
402
403
404
405
406
template <class Traits>
Flag ProblemStat<Traits>::
globalCoarsen(int n)
{
  Dune::Timer t;
  bool adapted = false;
407
  // TODO(FM): Find a less expensive alternative to the loop adaption
408
  for (int i = 0; i < n; ++i) {
409
    // mark all entities for coarsening
410
411
412
    for (const auto& element : elements(grid_->leafGridView()))
      grid_->mark(-1, element);

413
414
415
416
417
418
419
    bool adaptedInLoop = grid_->preAdapt();
    adaptedInLoop |= grid_->adapt();
    grid_->postAdapt();
    if (!adaptedInLoop)
      break;
    else
      adapted = true;
420
421
422
423
424
425
426
427
428
  }

  msg("globalCoarsen needed {} seconds", t.elapsed());
  return adapted ? MESH_ADAPTED : Flag(0);
}


// grid has globalRefine(int, AdaptDataHandleInterface&)
template <class G>
429
430
using HasGlobalRefineADHI = decltype(
  std::declval<G>().globalRefine(1,std::declval<typename G::ADHI&>()));
431
432
433

template <class Traits>
Flag ProblemStat<Traits>::
434
globalRefine(int n)
435
436
{
  Dune::Timer t;
437
438
439
440
  if constexpr (Dune::Std::is_detected<HasGlobalRefineADHI, Grid>::value)
    grid_->globalRefine(n, globalBasis_->globalRefineCallback());
  else
    grid_->globalRefine(n);
441
442

  msg("globalRefine needed {} seconds", t.elapsed());
443
  return n > 0 ? MESH_ADAPTED : Flag(0);
444
445
446
}


447
448
template <class Traits>
Flag ProblemStat<Traits>::
449
adaptGrid(AdaptInfo& /*adaptInfo*/)
450
451
452
{
  Dune::Timer t;

453
454
455
  bool adapted = grid_->preAdapt();
  adapted |= grid_->adapt();
  grid_->postAdapt();
456

457
  msg("adaptGrid needed {} seconds", t.elapsed());
458
  return adapted ? MESH_ADAPTED : Flag(0);
459
460
461
}


462
463
template <class Traits>
void ProblemStat<Traits>::
464
buildAfterAdapt(AdaptInfo& /*adaptInfo*/, Flag /*flag*/, bool asmMatrix, bool asmVector)
465
{
466
  Dune::Timer t;
467
  Dune::Timer t2;
468

469
  auto localView = globalBasis_->localView();
470
471
472
  for_each_node(localView.tree(), [&](auto&&, auto rowTp) -> void {
    for_each_node(localView.tree(), [&](auto&&, auto colTp) -> void {
      for (auto bc : boundaryConditions_[rowTp][colTp])
473
        bc->init();
474
475
    });
  });
476
477
478
479

  t2.reset();

  // 1. init matrix and rhs vector and initialize dirichlet boundary conditions
480
  systemMatrix_->init();
481
  rhs_->init(sizeInfo(*globalBasis_), asmVector);
482
483
484
485
486
487

  // statistic about system size
  if (Environment::mpiSize() > 1)
    msg("{} local DOFs, {} global DOFs", rhs_->localSize(), rhs_->globalSize());
  else
    msg("{} local DOFs", rhs_->localSize());
488
489

  // 2. traverse grid and assemble operators on the elements
Praetorius, Simon's avatar
Praetorius, Simon committed
490
  for (auto const& element : elements(gridView(), PartitionSet{})) {
491
    localView.bind(element);
492
493

    if (asmMatrix)
494
      systemMatrix_->assemble(localView, localView);
495
    if (asmVector)
496
      rhs_->assemble(localView);
497

498
    localView.unbind();
499
500
501
  }

  // 3. finish matrix insertion and apply dirichlet boundary conditions
502
503
  systemMatrix_->finish();
  rhs_->finish();
504

505
506
507
  info(2,"  assemble operators needed {} seconds", t2.elapsed());
  t2.reset();

508
  solution_->resize(sizeInfo(*globalBasis_));
509
510
  for_each_node(localView.tree(), [&](auto&&, auto rowTp) -> void {
    for_each_node(localView.tree(), [&](auto&&, auto colTp) -> void {
511
      // finish boundary condition
512
      for (auto bc : boundaryConditions_[rowTp][colTp])
513
        bc->apply(*systemMatrix_, *solution_, *rhs_);
514
515
    });
  });
516

517
518
  info(2,"  assemble boundary conditions needed {} seconds", t2.elapsed());

519
  msg("fill-in of assembled matrix: {}", systemMatrix_->nnz());
520
  msg("assemble needed {} seconds", t.elapsed());
521
}
522

523

524
525
template <class Traits>
void ProblemStat<Traits>::
526
writeFiles(AdaptInfo& adaptInfo, bool force)
527
{
528
  Dune::Timer t;
529
  for (auto writer : filewriter_)
Praetorius, Simon's avatar
Praetorius, Simon committed
530
    writer->write(adaptInfo, force);
531
  msg("writeFiles needed {} seconds", t.elapsed());
532
}
533

534
} // end namespace AMDiS