MeshDistributor.cc 68.2 KB
Newer Older
1
//
2
3
4
5
6
7
8
9
10
11
12
// Software License for AMDiS
//
// Copyright (c) 2010 Dresden University of Technology 
// All rights reserved.
// Authors: Simon Vey, Thomas Witkowski et al.
//
// This file is part of AMDiS
//
// See also license.opensource.txt in the distribution.


Thomas Witkowski's avatar
Thomas Witkowski committed
13
#include <algorithm>
14
15
#include <iostream>
#include <fstream>
16
17
#include <limits>
#include <stdint.h>
Thomas Witkowski's avatar
Thomas Witkowski committed
18
#include <boost/lexical_cast.hpp>
19
20
#include <boost/filesystem.hpp>

21
#include "parallel/MeshDistributor.h"
22
#include "parallel/MeshManipulation.h"
23
#include "parallel/ParallelDebug.h"
24
#include "parallel/StdMpi.h"
25
#include "parallel/ParMetisPartitioner.h"
26
27
28
#include "io/ElementFileWriter.h"
#include "io/MacroInfo.h"
#include "io/VtkWriter.h"
29
30
31
32
33
#include "Mesh.h"
#include "Traverse.h"
#include "ElInfo.h"
#include "Element.h"
#include "MacroElement.h"
34
35
#include "DOFMatrix.h"
#include "DOFVector.h"
36
#include "SystemVector.h"
37
#include "ElementDofIterator.h"
38
39
#include "ProblemStatBase.h"
#include "StandardProblemIteration.h"
40
#include "VertexVector.h"
41
#include "MeshStructure.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
42
43
#include "ProblemVec.h"
#include "ProblemInstat.h"
44
#include "Debug.h"
45

46
47
namespace AMDiS {

Thomas Witkowski's avatar
Thomas Witkowski committed
48
  using boost::lexical_cast;
49
  using namespace boost::filesystem;
Thomas Witkowski's avatar
Thomas Witkowski committed
50

51
52
53
54
55
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

56

57
58
59
60
61
62
63
64
  MeshDistributor::MeshDistributor(std::string str)
    : probStat(0),
      name(str),
      feSpace(NULL),
      mesh(NULL),
      refineManager(NULL),
      info(10),
      partitioner(NULL),
65
      nRankDofs(0),
66
      nOverallDofs(0),
67
      rstart(0),
68
      deserialized(false),
69
      writeSerializationFile(false),
70
      repartitioningAllowed(false),
71
      repartitionIthChange(20),
72
      nTimestepsAfterLastRepartitioning(0),
73
      repartCounter(0),
74
      debugOutputDir(""),
75
      lastMeshChangeIndex(0)
76
  {
77
    FUNCNAME("MeshDistributor::ParalleDomainBase()");
Thomas Witkowski's avatar
Thomas Witkowski committed
78

79
80
81
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
82
83
84
85

    int tmp = 0;
    GET_PARAMETER(0, name + "->repartitioning", "%d", &tmp);
    repartitioningAllowed = (tmp > 0);
86

87
88
    GET_PARAMETER(0, name + "->debug output dir", &debugOutputDir);
    GET_PARAMETER(0, name + "->repartition ith change", "%d", &repartitionIthChange);
89
90
91
92

    tmp = 0;
    GET_PARAMETER(0, name + "->log main rank", "%d", &tmp);
    Msg::outputMainRank = (tmp > 0);
93
94
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
95

96
  void MeshDistributor::initParallelization()
97
  {
98
    FUNCNAME("MeshDistributor::initParallelization()");
99
100
101
102

    TEST_EXIT(mpiSize > 1)
      ("Parallelization does not work with only one process!\n");

103
104
    TEST_EXIT(feSpace)("No FE space has been defined for the mesh distributor!\n");
    TEST_EXIT(mesh)("No mesh has been defined for the mesh distributor!\n");
105

106
107
    elObjects.setFeSpace(feSpace);

108
109
110
    // If the problem has been already read from a file, we need only to set
    // isRankDofs to all matrices and rhs vector and to remove periodic 
    // boundary conditions (if there are some).
111
    if (deserialized) {
112
113
      updateMacroElementInfo();

114
      setRankDofs();
115

116
      removePeriodicBoundaryConditions();
117

118
119
      macroElIndexMap.clear();
      macroElIndexTypeMap.clear();
120
121
122
123
124

      std::map<int, bool>& elementInRank = partitioner->getElementInRank();
      for (std::vector<MacroElement*>::iterator it = allMacroElements.begin();
	   it != allMacroElements.end(); ++it) {
	elementInRank[(*it)->getIndex()] = false;
125
126
127
128
	macroElIndexMap[(*it)->getIndex()] = (*it)->getElement();
	macroElIndexTypeMap[(*it)->getIndex()] = (*it)->getElType();
      }

129
130
131
132
      for (std::deque<MacroElement*>::iterator it = mesh->getMacroElements().begin();
	   it != mesh->getMacroElements().end(); ++it)
	elementInRank[(*it)->getIndex()] = true;      

133
      return;
134
    }
135

136
   
137
138
139
140
141
    // Test, if the mesh is the macro mesh only! Paritioning of the mesh is supported
    // only for macro meshes, so it will not work yet if the mesh is already refined
    // in some way.
    testForMacroMesh();

142
143
144
145
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

146
147
    // create an initial partitioning of the mesh
    partitioner->createPartitionData();
148

149
    // set the element weights, which are 1 at the very first begin
150
    setInitialElementWeights();
151
152
153

    // and now partition the mesh    
    partitioner->fillCoarsePartitionVec(&oldPartitionVec);
154
155
156
157

    bool partitioningSucceed = partitioner->partition(elemWeights, INITIAL);
    TEST_EXIT(partitioningSucceed)("Initial partitioning does not work!\n");

158
159
    partitioner->fillCoarsePartitionVec(&partitionVec);

160

Thomas Witkowski's avatar
Thomas Witkowski committed
161
#if (DEBUG != 0)
162
163
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
164
165
166
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
167

168
      if (writePartMesh > 0) {
169
170
	debug::writeElementIndexMesh(mesh, debugOutputDir + "elementIndex.vtu");
	writePartitioningMesh(debugOutputDir + "part.vtu");
171
      } else {
172
	MSG("Skip write part mesh!\n");
173
      }
174
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
175
#endif
176

177

178
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
179

180
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
181

182
#if (DEBUG != 0)
183
    ParallelDebug::printBoundaryInfo(*this);
184
185
#endif

186

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
187
188
189
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
190

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
191

192
193
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
194

195
196
197
198
199
200
    // We have to remove the VertexVectors, which contain periodic assoiciations, 
    // because they are not valid anymore after some macro elements have been removed
    // and the corresponding DOFs were deleted.
    for (std::map<BoundaryType, VertexVector*>::iterator it = mesh->getPeriodicAssociations().begin();
	 it != mesh->getPeriodicAssociations().end(); ++it)
      const_cast<DOFAdmin&>(mesh->getDofAdmin(0)).removeDOFContainer(dynamic_cast<DOFContainer*>(it->second));
201

202
    updateLocalGlobalNumbering();
203

204

205
206
    // === If in debug mode, make some tests. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
207
#if (DEBUG != 0)
208
    MSG("AMDiS runs in debug mode, so make some test ...\n");
209

210
    ParallelDebug::testAllElements(*this);
211
    debug::testSortedDofs(mesh, elMap);
212
213
    ParallelDebug::testInteriorBoundary(*this);
    ParallelDebug::testCommonDofs(*this, true);
214
    ParallelDebug::testGlobalIndexByCoords(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
215

216
    debug::writeMesh(feSpace, -1, debugOutputDir + "macro_mesh");   
217
218

    MSG("Debug mode tests finished!\n");
219
#endif
220

221

222
223
    // === Create periodic dof mapping, if there are periodic boundaries. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
224
    createPeriodicMap();    
225

226
227
228
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
229

230
    // === Global refinements. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
231

Thomas Witkowski's avatar
Thomas Witkowski committed
232
    int globalRefinement = 0;
233
    GET_PARAMETER(0, mesh->getName() + "->global refinements", "%d", &globalRefinement);
Thomas Witkowski's avatar
Thomas Witkowski committed
234

Thomas Witkowski's avatar
Thomas Witkowski committed
235
    if (globalRefinement > 0) {
236
      refineManager->globalRefine(mesh, globalRefinement);
237

238
      updateLocalGlobalNumbering();
239
240

     
241
242
      // === Update periodic mapping, if there are periodic boundaries. ===     

243
      createPeriodicMap();
Thomas Witkowski's avatar
Thomas Witkowski committed
244
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
245

246

Thomas Witkowski's avatar
Thomas Witkowski committed
247
248
    /// === Set DOF rank information to all matrices and vectors. ===

249
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
250

251

Thomas Witkowski's avatar
Thomas Witkowski committed
252
253
    // === Remove periodic boundary conditions in sequential problem definition. ===

254
    removePeriodicBoundaryConditions();
255
256
  }

257

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
  void MeshDistributor::addProblemStat(ProblemVec *probVec)
  {
    FUNCNAME("MeshDistributor::addProblemVec()");

    if (feSpace != NULL) {
      std::vector<FiniteElemSpace*> feSpaces = probVec->getFeSpaces();
      for (unsigned int i = 0; i < feSpaces.size(); i++) {
	TEST_EXIT(feSpace == feSpaces[i])
	  ("Parallelizaton is not supported for multiple FE spaces!\n");
      }
    } else {
      feSpace = probVec->getFeSpace(0);
      mesh = feSpace->getMesh();
      info = probVec->getInfo();
      
      TEST_EXIT(mesh->getNumberOfDOFAdmin() == 1)
	("Only meshes with one DOFAdmin are supported!\n");
275
      TEST_EXIT(mesh->getDofAdmin(0).getNumberOfPreDofs(VERTEX) == 0)
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
	("Wrong pre dof number for DOFAdmin!\n");
      
      switch (mesh->getDim()) {
      case 2:
	refineManager = new RefinementManager2d();
	break;
      case 3:
	refineManager = new RefinementManager3d();
	break;
      default:
	ERROR_EXIT("This should not happen for dim = %d!\n", mesh->getDim());
      }

      partitioner = new ParMetisPartitioner(mesh, &mpiComm);
    }

    // Create parallel serialization file writer, if needed.
    int writeSerialization = 0;
294
295
296
    GET_PARAMETER(0, probVec->getName() + "->output->write serialization", "%d", 
		  &writeSerialization);
    if (writeSerialization && !writeSerializationFile) {
297
298
299
300
301
      std::string filename = "";
      GET_PARAMETER(0, name + "->output->serialization filename", &filename);
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel serialization file!\n");
302
303
304
305
306

      int tsModulo = -1;
      GET_PARAMETER(0, probVec->getName() + "->output->write every i-th timestep", 
		    "%d", &tsModulo);
      
307
      probVec->getFileWriterList().push_back(new Serializer<MeshDistributor>(this, filename, tsModulo));
308
309
      writeSerializationFile = true;
    }    
310
311

    int readSerialization = 0;
312
313
    GET_PARAMETER(0, probVec->getName() + "->input->read serialization", "%d", 
		  &readSerialization);
314
315
316
317
    if (readSerialization) {
      std::string filename = "";
      GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
      filename += ".p" + lexical_cast<std::string>(mpiRank);
318
      MSG("Start deserialization with %s\n", filename.c_str());
319
      std::ifstream in(filename.c_str());
320
321
322
323

      TEST_EXIT(!in.fail())("Could not open deserialization file: %s\n",
			    filename.c_str());

324
      probVec->deserialize(in);
325
      in.close();
326
327
      MSG("Deserialization from file: %s\n", filename.c_str());

328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
      filename = "";
      GET_PARAMETER(0, name + "->input->serialization filename", &filename);
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel deserialization file!\n");
      
      std::string rankFilename = filename + ".p" + lexical_cast<std::string>(mpiRank);
      in.open(rankFilename.c_str());
      
      TEST_EXIT(!in.fail())("Could not open parallel deserialization file: %s\n",
			    filename.c_str());
      
      deserialize(in);
      in.close();
      MSG("Deserializtion of mesh distributor from file: %s\n", rankFilename.c_str());
      deserialized = true;
344
345
346
347
348
349
    }

    probStat.push_back(probVec);
  }


350
  void MeshDistributor::exitParallelization()
351
  {}
352

353
  
354
  void MeshDistributor::testForMacroMesh()
355
  {
356
    FUNCNAME("MeshDistributor::testForMacroMesh()");
357
358
359
360
361
362
363

    int nMacroElements = 0;

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
    while (elInfo) {
      TEST_EXIT(elInfo->getLevel() == 0)
364
	("Mesh is already refined! This does not work with parallelization!\n");
365
366
367

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
368
369
370
371
372
373
374
375
376
377
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

    TEST_EXIT(nMacroElements >= mpiSize)
      ("The mesh has less macro elements than number of mpi processes!\n");
  }

378

379
  void MeshDistributor::synchVector(DOFVector<double> &vec)
380
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
381
    StdMpi<std::vector<double> > stdMpi(mpiComm);
382
383

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
384
	 sendIt != sendDofs.end(); ++sendIt) {
385
      std::vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
386
387
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
388
      
Thomas Witkowski's avatar
Thomas Witkowski committed
389
390
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
391
392
393
394

      stdMpi.send(sendIt->first, dofs);
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
395
396
397
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
398

Thomas Witkowski's avatar
Thomas Witkowski committed
399
    stdMpi.startCommunication<double>(MPI_DOUBLE);
400

Thomas Witkowski's avatar
Thomas Witkowski committed
401
402
403
404
405
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      for (unsigned int i = 0; i < recvIt->second.size(); i++)
	vec[*(recvIt->second)[i]] = stdMpi.getRecvData(recvIt->first)[i];
  }
406
407


408
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
409
  {
410
    int nComponents = vec.getSize();
Thomas Witkowski's avatar
Thomas Witkowski committed
411
412
413
414
415
416
417
418
419
420
421
422
    StdMpi<std::vector<double> > stdMpi(mpiComm);

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
	 sendIt != sendDofs.end(); ++sendIt) {
      std::vector<double> dofs;
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nComponents * nSendDofs);
      
      for (int i = 0; i < nComponents; i++) {
	DOFVector<double> *dofvec = vec.getDOFVector(i);
	for (int j = 0; j < nSendDofs; j++)
	  dofs.push_back((*dofvec)[*((sendIt->second)[j])]);
423
424
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
425
      stdMpi.send(sendIt->first, dofs);
426
427
428
    }

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
429
430
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size() * nComponents);
431

Thomas Witkowski's avatar
Thomas Witkowski committed
432
    stdMpi.startCommunication<double>(MPI_DOUBLE);
433
434

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
435
436
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
437
438

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
439
440
441
442
443
      for (int i = 0; i < nComponents; i++) {
	DOFVector<double> *dofvec = vec.getDOFVector(i);
 	for (int j = 0; j < nRecvDofs; j++)
	  (*dofvec)[*(recvIt->second)[j]] = 
	    stdMpi.getRecvData(recvIt->first)[counter++];
444
445
446
447
      }
    }
  }

448

449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
  void MeshDistributor::setRankDofs()
  {
    for (unsigned int i = 0; i < probStat.size(); i++) {
      int nComponents = probStat[i]->getNumComponents();
      for (int j = 0; j < nComponents; j++) {
	for (int k = 0; k < nComponents; k++)
	  if (probStat[i]->getSystemMatrix(j, k))
	    probStat[i]->getSystemMatrix(j, k)->setRankDofs(isRankDof);

	TEST_EXIT_DBG(probStat[i]->getRhs()->getDOFVector(j))("No RHS vector!\n");
	TEST_EXIT_DBG(probStat[i]->getSolution()->getDOFVector(j))("No solution vector!\n");
	
	probStat[i]->getRhs()->getDOFVector(j)->setRankDofs(isRankDof);
	probStat[i]->getSolution()->getDOFVector(j)->setRankDofs(isRankDof);
      }
    }
  }


468
469
  void MeshDistributor::removePeriodicBoundaryConditions()
  {
470
471
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

472
473
474
475
476
477
478
479
    // Remove periodic boundaries in boundary manager on matrices and vectors.
    for (unsigned int i = 0; i < probStat.size(); i++) {
      int nComponents = probStat[i]->getNumComponents();

      for (int j = 0; j < nComponents; j++) {
	for (int k = 0; k < nComponents; k++) {
	  DOFMatrix* mat = probStat[i]->getSystemMatrix(j, k);
	  if (mat && mat->getBoundaryManager())
480
	    removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
	}
	
	if (probStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(probStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
	
	if (probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
      }
    }

    // Remove periodic boundaries on elements in mesh.
    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh,  -1, Mesh::CALL_EVERY_EL_PREORDER);
    while (elInfo) {
      elInfo->getElement()->deleteElementData(PERIODIC);
      elInfo = stack.traverseNext(elInfo);
    }    
498
499
500

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
501
502
503
504
  }


  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
505
506
507
508
509
510
511
512
513
514
515
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


516
  void MeshDistributor::checkMeshChange()
517
  {
518
    FUNCNAME("MeshDistributor::checkMeshChange()");    
519

520
#if (DEBUG != 0)
521
    debug::writeMesh(feSpace, -1, debugOutputDir + "before_check_mesh");
522
523
#endif

524
525
    double first = MPI::Wtime();

526
527
528
529
530
    // === If mesh has not been changed on all ranks, return. ===

    int recvAllValues = 0;
    int sendValue = static_cast<int>(mesh->getChangeIndex() != lastMeshChangeIndex);
    mpiComm.Allreduce(&sendValue, &recvAllValues, 1, MPI_INT, MPI_SUM);
531

532
    if (recvAllValues == 0)
533
534
      return;

535
536
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
537
   
538
539
540
    do {
      // To check the interior boundaries, the ownership of the boundaries is not 
      // important. Therefore, we add all boundaries to one boundary container.
541
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
542
543

      for (InteriorBoundary::iterator it(myIntBoundary); !it.end(); ++it)
544
545
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
546
 	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
547
548

      for (InteriorBoundary::iterator it(otherIntBoundary); !it.end(); ++it)
549
550
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
551
	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
552

553
554
      for (InteriorBoundary::iterator it(periodicBoundary); !it.end(); ++it) {
	if (it.getRank() == mpiRank) {
555
	  WARNING("Na, du weisst schon!\n");
556
557
558
559
560
561
	} else {
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
	    allBound[it.getRank()].push_back(*it);	
	}
      }
562

563

564
      // === Check the boundaries and adapt mesh if necessary. ===
565
566
567
568
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

569
570
571
572
573
574
575
      bool meshChanged = checkAndAdaptBoundary(allBound);

      // === Check on all ranks if at least one rank's mesh has changed. ===

      int sendValue = static_cast<int>(!meshChanged);
      recvAllValues = 0;
      mpiComm.Allreduce(&sendValue, &recvAllValues, 1, MPI_INT, MPI_SUM);
576
577
578
579

#if (DEBUG != 0)
      MSG("Mesh changed on %d ranks!\n", recvAllValues);
#endif
580
    } while (recvAllValues != 0);
581

582
#if (DEBUG != 0)
583
    debug::writeMesh(feSpace, -1, debugOutputDir + "mesh");
584
585
586
#endif

    // === Because the mesh has been changed, update the DOF numbering and mappings. ===
587

588
589
    updateLocalGlobalNumbering();

590
591
592

    // === Update periodic mapping, if there are periodic boundaries. ===

593
    createPeriodicMap();    
594

595
596
597
598
599

    INFO(info, 8)("Parallel mesh adaption needed %.5f seconds\n", 
		  MPI::Wtime() - first);


600
601
    // === The mesh has changed, so check if it is required to repartition the mesh. ===

602
603
604
    nTimestepsAfterLastRepartitioning++;

    if (repartitioningAllowed) {
605
      if (nTimestepsAfterLastRepartitioning >= repartitionIthChange) {
606
607
	repartitionMesh();
	nTimestepsAfterLastRepartitioning = 0;
608
      }
609
    }
610
611
612
  }

  
613
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
614
  {
615
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
616
617
618
619
620
621

    // === Create mesh structure codes for all ranks boundary elements. ===
       
    std::map<int, MeshCodeVec> sendCodes;
   
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
622

623
624
625
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
626
	elCode.init(boundIt->rankObj);
627
628
629
630
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
631
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
632
    stdMpi.send(sendCodes);
633
    stdMpi.recv(allBound);
634
    stdMpi.startCommunication<uint64_t>(MPI_UNSIGNED_LONG);
635
 
636
    // === Compare received mesh structure codes. ===
637
    
638
639
    bool meshFitTogether = true;

640
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
641
     
642
643
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
644
      
645
646
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
647

648
649
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
650

651
652
	if (elCode.getCode() != recvCodes[i].getCode()) {
	  TEST_EXIT_DBG(refineManager)("Refinement manager is not set correctly!\n");
653

654
655
656
657
658
659
	  bool b = startFitElementToMeshCode(recvCodes[i], 
					     boundIt->rankObj.el,
					     boundIt->rankObj.subObj,
					     boundIt->rankObj.ithObj, 
					     boundIt->rankObj.elType,
					     boundIt->rankObj.reverseMode);
660

661
	  if (b)
662
	    meshFitTogether = false;	  
663
 	}
664

665
	i++;
666
667
668
      }
    }

669
    return meshFitTogether;
670
  }
671
672


673
674
675
676
677
678
  bool MeshDistributor::startFitElementToMeshCode(MeshStructure &code, 
						  Element *el, 
						  GeoIndex subObj,
						  int ithObj, 
						  int elType,
						  bool reverseMode)
679
  {
680
    FUNCNAME("MeshDistributor::startFitElementToMeshCode()");
681

682
683
    TEST_EXIT_DBG(el)("No element given!\n");

684
685
    // If the code is empty, the element does not matter and the function can
    // return without chaning the mesh.
686
687
    if (code.empty())
      return false;
688

689
690
691
692
693
    // s0 and s1 are the number of the edge/face in both child of the element,
    // which contain the edge/face the function has to traverse through. If the
    // edge/face is not contained in one of the children, s0 or s1 is -1.
    int s0 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s1 = el->getSubObjOfChild(1, subObj, ithObj, elType);
694

695
    TEST_EXIT_DBG(s0 != -1 || s1 != -1)("This should not happen!\n");
696

697
    bool meshChanged = false;
698
699
700
    Flag traverseFlag = 
      Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND;

701
702
703
704
705
    // Test for reverse mode, in which the left and right children of elements
    // are flipped.
    if (reverseMode)
      traverseFlag |= Mesh::CALL_REVERSE_MODE;    

706

707
708
709
710
711
    // === If the edge/face is contained in both children. ===

    if (s0 != -1 && s1 != -1) {
      // Create traverse stack and traverse within the mesh until the element,
      // which should be fitted to the mesh structure code, is reached.
712
      TraverseStack stack;
713
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
714
715
      while (elInfo && elInfo->getElement() != el)
	elInfo = stack.traverseNext(elInfo);      
716

717
718
      TEST_EXIT_DBG(elInfo->getElement() == el)("This should not happen!\n");

719
      meshChanged = fitElementToMeshCode(code, stack, subObj, ithObj, reverseMode);
720
721
      return meshChanged;
    }
722

723
724
725

    // === The edge/face is contained in only on of the both children. ===

726
    if (el->isLeaf()) {
727
728

      // If element is leaf and code contains only one leaf element, we are finished.
729
730
731
      if (code.getNumElements() == 1 && code.isLeafElement())
	return false;     

732
      // Create traverse stack and traverse the mesh to the element.
733
      TraverseStack stack;
734
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
735
736
      while (elInfo && elInfo->getElement() != el)
	elInfo = stack.traverseNext(elInfo);      
737
738
739

      TEST_EXIT_DBG(elInfo)("This should not happen!\n");

740
      // Code is not leaf, therefore refine the element.
741
      el->setMark(1);
742
743
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
744
      refineManager->refineFunction(elInfo);
745
      meshChanged = true;
746
    }
747

748
749
    Element *child0 = el->getFirstChild();
    Element *child1 = el->getSecondChild();
750
751
752
753
    if (reverseMode) {
      std::swap(s0, s1);
      std::swap(child0, child1);    
    }
754

755
756
757
    // === We know that the edge/face is contained in only one of the children. ===
    // === Therefore, traverse the mesh to this children and fit this element   ===
    // === To the mesh structure code.                                          ===
758

759
760
    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
761

762
763
764
    if (s0 != -1) {
      while (elInfo && elInfo->getElement() != child0)
	elInfo = stack.traverseNext(elInfo);     
765

766
767
768
769
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s0, reverseMode);
    } else {
      while (elInfo && elInfo->getElement() != child1) 
	elInfo = stack.traverseNext(elInfo);      
770

771
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s1, reverseMode);
772
773
    }

774

775
    return meshChanged;
776
777
  }

778

779
780
781
782
783
  bool MeshDistributor::fitElementToMeshCode(MeshStructure &code, 
					     TraverseStack &stack,
					     GeoIndex subObj,
					     int ithObj, 
					     bool reverseMode)
784
  {
785
786
787
788
    FUNCNAME("MeshDistributor::fitElementToMeshCode()");


    // === Test if there are more elements in stack to check with the code. ===
789

790
791
    ElInfo *elInfo = stack.getElInfo();
    if (!elInfo)
792
      return false;
793

794
795
796
797

    // === Test if code contains a leaf element. If this is the case, the ===
    // === current element is finished. Traverse the mesh to the next     ===
    // === coarser element.                                               ===
798
799
800
801
802
803
804

    if (code.isLeafElement()) {
      int level = elInfo->getLevel();

      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getLevel() > level);
805

806
      return false;
807
    }
808

809
810
811
812
813
814

    bool meshChanged = false;
    Element *el = elInfo->getElement();


    // === If element is leaf (and the code is not), refine the element. ===
815

816
    if (el->isLeaf()) {
817
818
      TEST_EXIT_DBG(elInfo->getLevel() < 255)("This should not happen!\n");

819
      el->setMark(1);
820
821
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
822
      refineManager->refineFunction(elInfo);
823
      meshChanged = true;
824
825
    }

826
827
828
829
830
831

    // === Continue fitting the mesh structure code to the children of the ===
    // === current element.                                                ===

    int s0 = el->getSubObjOfChild(0, subObj, ithObj, elInfo->getType());
    int s1 = el->getSubObjOfChild(1, subObj, ithObj, elInfo->getType());
832
833
834
    Element *child0 = el->getFirstChild();
    Element *child1 = el->getSecondChild();
    if (reverseMode) {
835
      std::swap(s0, s1);
836
837
      std::swap(child0, child1);
    }
838

839
840
841
842
843
844
845
    
    // === Traverse left child. ===

    if (s0 != -1) {
      // The edge/face is contained in the left child, therefore fit this
      // child to the mesh structure code.

846
      stack.traverseNext(elInfo);
847
      code.nextElement();
848
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s0, reverseMode);
849
850
      elInfo = stack.getElInfo();
    } else {
851
852
853
854
      // The edge/face is not contained in the left child. Hence we need
      // to traverse through all subelements of the left child until we get
      // the second child of the current element.

855
856
      do {
	elInfo = stack.traverseNext(elInfo);
857
858
859
      } while (elInfo && elInfo->getElement() != child1); 

      TEST_EXIT_DBG(elInfo != NULL)("This should not happen!\n");
860
861
    }  

862
863
864
865
866
867
868
869
870
871
    TEST_EXIT_DBG(elInfo->getElement() == child1)
      ("Got wrong child with idx = %d! Searched for child idx = %d\n",
       elInfo->getElement()->getIndex(), child1->getIndex());


    // === Traverse right child. ===

    if (s1 != -1) {
      // The edge/face is contained in the right child, therefore fit this
      // child to the mesh structure code.
872
873

      code.nextElement();
874
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s1, reverseMode);
875
    } else {
876
877
878
879
      // The edge/face is not contained in the right child. Hence we need
      // to traverse through all subelements of the right child until we have
      // finished traversing the current element with all its subelements.

Thomas Witkowski's avatar