MeshDistributor.cc 62.5 KB
Newer Older
Thomas Witkowski's avatar
Thomas Witkowski committed
1
#include <algorithm>
2
3
#include <iostream>
#include <fstream>
4
5
#include <limits>
#include <stdint.h>
Thomas Witkowski's avatar
Thomas Witkowski committed
6
#include <boost/lexical_cast.hpp>
7
8
#include <boost/filesystem.hpp>

9
#include "parallel/MeshDistributor.h"
10
#include "parallel/MeshManipulation.h"
11
#include "parallel/ParallelDebug.h"
12
#include "parallel/StdMpi.h"
13
#include "parallel/ParMetisPartitioner.h"
14
15
16
#include "io/ElementFileWriter.h"
#include "io/MacroInfo.h"
#include "io/VtkWriter.h"
17
18
19
20
21
#include "Mesh.h"
#include "Traverse.h"
#include "ElInfo.h"
#include "Element.h"
#include "MacroElement.h"
22
23
#include "DOFMatrix.h"
#include "DOFVector.h"
24
#include "SystemVector.h"
25
#include "ElementDofIterator.h"
26
27
#include "ProblemStatBase.h"
#include "StandardProblemIteration.h"
28
#include "VertexVector.h"
29
#include "MeshStructure.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
30
31
#include "ProblemVec.h"
#include "ProblemInstat.h"
32
#include "Debug.h"
33

34
35
namespace AMDiS {

Thomas Witkowski's avatar
Thomas Witkowski committed
36
  using boost::lexical_cast;
37
  using namespace boost::filesystem;
Thomas Witkowski's avatar
Thomas Witkowski committed
38

39
40
41
42
43
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

44

45
46
47
48
49
50
51
52
  MeshDistributor::MeshDistributor(std::string str)
    : probStat(0),
      name(str),
      feSpace(NULL),
      mesh(NULL),
      refineManager(NULL),
      info(10),
      partitioner(NULL),
53
      nRankDofs(0),
54
      nOverallDofs(0),
55
      rstart(0),
56
      deserialized(false),
57
      writeSerializationFile(false),
58
      repartitioningAllowed(false),
59
      nTimestepsAfterLastRepartitioning(0),
60
      repartCounter(0),
61
      lastMeshChangeIndex(0)
62
  {
63
    FUNCNAME("MeshDistributor::ParalleDomainBase()");
Thomas Witkowski's avatar
Thomas Witkowski committed
64

65
66
67
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
68
69
70
71

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

Thomas Witkowski's avatar
Thomas Witkowski committed
74

75
  void MeshDistributor::initParallelization()
76
  {
77
    FUNCNAME("MeshDistributor::initParallelization()");
78
79
80
81

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

82
83
    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");
84

85
86
87
    // 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).
88
    if (deserialized) {
89
      setRankDofs();
90
      removePeriodicBoundaryConditions();
91

92
      return;
93
    }
94

95
   
96
97
98
99
100
    // 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();

101
102
103
104
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

105
106
    // create an initial partitioning of the mesh
    partitioner->createPartitionData();
107

108
    // set the element weights, which are 1 at the very first begin
109
    setInitialElementWeights();
110
111
112
113
114
115

    // and now partition the mesh    
    partitioner->fillCoarsePartitionVec(&oldPartitionVec);
    partitioner->partition(&elemWeights, INITIAL);
    partitioner->fillCoarsePartitionVec(&partitionVec);

116

Thomas Witkowski's avatar
Thomas Witkowski committed
117
#if (DEBUG != 0)
118
119
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
120
121
122
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
123

124
125
      if (writePartMesh > 0) {
	debug::writeElementIndexMesh(mesh, "elementIndex.vtu");
126
	writePartitioningMesh("part.vtu");
127
      } else {
128
	MSG("Skip write part mesh!\n");
129
      }
130
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
131
#endif
132

133

134
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
135

136
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
137

138
#if (DEBUG != 0)
139
    ParallelDebug::printBoundaryInfo(*this);
140
141
#endif

142

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
143
144
145
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
146

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
147

148
149
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
150

151
152
153
154
155
156
    // 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));
157

158
    updateLocalGlobalNumbering();
159

160

161
162
    // === If in debug mode, make some tests. ===

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

166
    ParallelDebug::testAllElements(*this);
167
    debug::testSortedDofs(mesh, elMap);
168
169
    ParallelDebug::testInteriorBoundary(*this);
    ParallelDebug::testCommonDofs(*this, true);
170
    ParallelDebug::testGlobalIndexByCoords(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
171

172
    debug::writeMesh(feSpace, -1, "macro_mesh");   
173
174

    MSG("Debug mode tests finished!\n");
175
#endif
176

177

178
179
    // === Create periodic dof mapping, if there are periodic boundaries. ===

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

182
    // === Global refinements. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
183

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

Thomas Witkowski's avatar
Thomas Witkowski committed
187
    if (globalRefinement > 0) {
188
      refineManager->globalRefine(mesh, globalRefinement);
189

190
#if (DEBUG != 0)
191
      debug::writeMesh(feSpace, -1, "gr_mesh");
192
193
#endif

194
      updateLocalGlobalNumbering();
195
196

     
197
      // === Update periodic mapping, if there are periodic boundaries. ===
198
      
199
      createPeriodicMap();
Thomas Witkowski's avatar
Thomas Witkowski committed
200
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
201

202

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

205
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
206

207

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

210
    removePeriodicBoundaryConditions();
211
212
  }

213

214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
  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");
231
      TEST_EXIT(mesh->getDofAdmin(0).getNumberOfPreDOFs(0) == 0)
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
	("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;
250
251
252
    GET_PARAMETER(0, probVec->getName() + "->output->write serialization", "%d", 
		  &writeSerialization);
    if (writeSerialization && !writeSerializationFile) {
253
254
255
256
257
      std::string filename = "";
      GET_PARAMETER(0, name + "->output->serialization filename", &filename);
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel serialization file!\n");
258
259
260
261
262

      int tsModulo = -1;
      GET_PARAMETER(0, probVec->getName() + "->output->write every i-th timestep", 
		    "%d", &tsModulo);
      
263
      probVec->getFileWriterList().push_back(new Serializer<MeshDistributor>(this, filename, tsModulo));
264
265
      writeSerializationFile = true;
    }    
266
267

    int readSerialization = 0;
268
269
    GET_PARAMETER(0, probVec->getName() + "->input->read serialization", "%d", 
		  &readSerialization);
270
271
272
273
    if (readSerialization) {
      std::string filename = "";
      GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
      filename += ".p" + lexical_cast<std::string>(mpiRank);
274
      MSG("Start deserialization with %s\n", filename.c_str());
275
      std::ifstream in(filename.c_str());
276
277
278
279

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

280
      probVec->deserialize(in);
281
      in.close();
282
283
      MSG("Deserialization from file: %s\n", filename.c_str());

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
      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;
300
301
302
303
304
305
    }

    probStat.push_back(probVec);
  }


306
  void MeshDistributor::exitParallelization()
307
  {}
308

309
  
310
  void MeshDistributor::testForMacroMesh()
311
  {
312
    FUNCNAME("MeshDistributor::testForMacroMesh()");
313
314
315
316
317
318
319

    int nMacroElements = 0;

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

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
324
325
326
327
328
329
330
331
332
333
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

334

335
  void MeshDistributor::synchVector(DOFVector<double> &vec)
336
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
337
    StdMpi<std::vector<double> > stdMpi(mpiComm);
338
339

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
340
	 sendIt != sendDofs.end(); ++sendIt) {
341
      std::vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
342
343
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
344
      
Thomas Witkowski's avatar
Thomas Witkowski committed
345
346
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
347
348
349
350

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

Thomas Witkowski's avatar
Thomas Witkowski committed
351
352
353
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
354

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

Thomas Witkowski's avatar
Thomas Witkowski committed
357
358
359
360
361
    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];
  }
362
363


364
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
365
  {
366
    int nComponents = vec.getSize();
Thomas Witkowski's avatar
Thomas Witkowski committed
367
368
369
370
371
372
373
374
375
376
377
378
    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])]);
379
380
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
381
      stdMpi.send(sendIt->first, dofs);
382
383
384
    }

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

Thomas Witkowski's avatar
Thomas Witkowski committed
388
    stdMpi.startCommunication<double>(MPI_DOUBLE);
389
390

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
391
392
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
393
394

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
395
396
397
398
399
      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++];
400
401
402
403
      }
    }
  }

404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  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);
      }
    }
  }


424
425
  void MeshDistributor::removePeriodicBoundaryConditions()
  {
426
427
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

428
429
430
431
432
433
434
435
    // 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())
436
	    removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
	}
	
	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);
    }    
454
455
456

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
457
458
459
460
  }


  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
461
462
463
464
465
466
467
468
469
470
471
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


472
  void MeshDistributor::checkMeshChange()
473
  {
474
    FUNCNAME("MeshDistributor::checkMeshChange()");    
475

476
477
478
479
#if (DEBUG != 0)
    debug::writeMesh(feSpace, -1, "before_check_mesh");
#endif

480
481
482
483
484
    // === 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);
485

486
    if (recvAllValues == 0)
487
488
      return;

489
490
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
491

492
493
494
495
496
    clock_t first = clock();
    
    do {
      // To check the interior boundaries, the ownership of the boundaries is not 
      // important. Therefore, we add all boundaries to one boundary container.
497
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
498
499

      for (InteriorBoundary::iterator it(myIntBoundary); !it.end(); ++it)
500
501
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
502
 	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
503
504

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

509
      for (InteriorBoundary::iterator it(periodicBoundary); !it.end(); ++it)
510
511
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
512
 	  allBound[it.getRank()].push_back(*it);	
513

514

515
      // === Check the boundaries and adapt mesh if necessary. ===
516
517
518
519
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

520
521
522
523
524
525
526
      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);
527
528
529
530

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

533
#if (DEBUG != 0)
534
    debug::writeMesh(feSpace, -1, "mesh");
535
536
537
538
539
540
#endif

    INFO(info, 8)("Parallel mesh adaption needed %.5f seconds\n", 
		  TIME_USED(first, clock()));

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

542
543
    updateLocalGlobalNumbering();

544
545
546
547

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

    createPeriodicMap();
548
549
550
551


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

552
553
554
555
556
557
558
559
    nTimestepsAfterLastRepartitioning++;

    if (repartitioningAllowed) {
      if (nTimestepsAfterLastRepartitioning >= 20) {
	repartitionMesh();
	nTimestepsAfterLastRepartitioning = 0;
      }
    }
560
561
562
  }

  
563
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
564
  {
565
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
566
567
568
569
570
571

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

573
574
575
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
576
	elCode.init(boundIt->rankObj);
577
578
579
580
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
581
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
582
    stdMpi.send(sendCodes);
583
    stdMpi.recv(allBound);
584
    stdMpi.startCommunication<uint64_t>(MPI_UNSIGNED_LONG);
585
 
586
    // === Compare received mesh structure codes. ===
587
    
588
589
    bool meshFitTogether = true;

590
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
591
     
592
593
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
594
      
595
596
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
597

598
599
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
600

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

604
605
606
607
608
609
	  bool b = startFitElementToMeshCode(recvCodes[i], 
					     boundIt->rankObj.el,
					     boundIt->rankObj.subObj,
					     boundIt->rankObj.ithObj, 
					     boundIt->rankObj.elType,
					     boundIt->rankObj.reverseMode);
610

611
	  if (b)
612
	    meshFitTogether = false;	  
613
 	}
614

615
	i++;
616
617
618
      }
    }

619
    return meshFitTogether;
620
  }
621
622


623
624
625
626
627
628
  bool MeshDistributor::startFitElementToMeshCode(MeshStructure &code, 
						  Element *el, 
						  GeoIndex subObj,
						  int ithObj, 
						  int elType,
						  bool reverseMode)
629
  {
630
    FUNCNAME("MeshDistributor::startFitElementToMeshCode()");
631

632
633
    TEST_EXIT_DBG(el)("No element given!\n");

634
635
    // If the code is empty, the element does not matter and the function can
    // return without chaning the mesh.
636
637
    if (code.empty())
      return false;
638

639
640
641
642
643
    // 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);
644

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

647
    bool meshChanged = false;
648
649
650
    Flag traverseFlag = 
      Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND;

651
652
653
654
655
    // Test for reverse mode, in which the left and right children of elements
    // are flipped.
    if (reverseMode)
      traverseFlag |= Mesh::CALL_REVERSE_MODE;    

656

657
658
659
660
661
    // === 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.
662
      TraverseStack stack;
663
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
664
665
      while (elInfo && elInfo->getElement() != el)
	elInfo = stack.traverseNext(elInfo);      
666

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

669
      meshChanged = fitElementToMeshCode(code, stack, subObj, ithObj, reverseMode);
670
671
      return meshChanged;
    }
672

673
674
675

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

676
    if (el->isLeaf()) {
677
678

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

682
      // Create traverse stack and traverse the mesh to the element.
683
      TraverseStack stack;
684
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
685
686
      while (elInfo && elInfo->getElement() != el)
	elInfo = stack.traverseNext(elInfo);      
687
688
689

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

690
      // Code is not leaf, therefore refine the element.
691
      el->setMark(1);
692
693
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
694
      refineManager->refineFunction(elInfo);
695
      meshChanged = true;
696
    }
697

698
699
    Element *child0 = el->getFirstChild();
    Element *child1 = el->getSecondChild();
700
701
702
703
    if (reverseMode) {
      std::swap(s0, s1);
      std::swap(child0, child1);    
    }
704

705
706
707
    // === 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.                                          ===
708

709
710
    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
711

712
713
714
    if (s0 != -1) {
      while (elInfo && elInfo->getElement() != child0)
	elInfo = stack.traverseNext(elInfo);     
715

716
717
718
719
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s0, reverseMode);
    } else {
      while (elInfo && elInfo->getElement() != child1) 
	elInfo = stack.traverseNext(elInfo);      
720

721
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s1, reverseMode);
722
723
    }

724

725
    return meshChanged;
726
727
  }

728

729
730
731
732
733
  bool MeshDistributor::fitElementToMeshCode(MeshStructure &code, 
					     TraverseStack &stack,
					     GeoIndex subObj,
					     int ithObj, 
					     bool reverseMode)
734
  {
735
736
737
738
    FUNCNAME("MeshDistributor::fitElementToMeshCode()");


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

740
741
    ElInfo *elInfo = stack.getElInfo();
    if (!elInfo)
742
      return false;
743

744
745
746
747

    // === 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.                                               ===
748
749
750
751
752
753
754

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

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

756
      return false;
757
    }
758

759
760
761
762
763
764

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


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

766
    if (el->isLeaf()) {
767
768
      TEST_EXIT_DBG(elInfo->getLevel() < 255)("This should not happen!\n");

769
      el->setMark(1);
770
771
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
772
      refineManager->refineFunction(elInfo);
773
      meshChanged = true;
774
775
    }

776
777
778
779
780
781

    // === 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());
782
783
784
    Element *child0 = el->getFirstChild();
    Element *child1 = el->getSecondChild();
    if (reverseMode) {
785
      std::swap(s0, s1);
786
787
      std::swap(child0, child1);
    }
788

789
790
791
792
793
794
795
    
    // === Traverse left child. ===

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

796
      stack.traverseNext(elInfo);
797
      code.nextElement();
798
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s0, reverseMode);
799
800
      elInfo = stack.getElInfo();
    } else {
801
802
803
804
      // 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.

805
806
      do {
	elInfo = stack.traverseNext(elInfo);
807
808
809
      } while (elInfo && elInfo->getElement() != child1); 

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

812
813
814
815
816
817
818
819
820
821
    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.
822
823

      code.nextElement();
824
      meshChanged |= fitElementToMeshCode(code, stack, subObj, s1, reverseMode);
825
    } else {
826
827
828
829
      // 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.

830
      int level = elInfo->getLevel();
831

832
833
834
835
      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getLevel() > level);
    }
836

837
838

    return meshChanged;
839
840
  }

841
  
842
  void MeshDistributor::serialize(std::ostream &out, DofContainer &data)
Thomas Witkowski's avatar
Thomas Witkowski committed
843
  {    
844
    int vecSize = data.size();
845
    SerUtil::serialize(out, vecSize);
846
847
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = (*data[i]);
848
      SerUtil::serialize(out, dofIndex);
849
850
851
852
    }
  }


853
  void MeshDistributor::deserialize(std::istream &in, DofContainer &data,
854
				    std::map<int, const DegreeOfFreedom*> &dofMap)
855
  {
856
    FUNCNAME("MeshDistributor::deserialize()");
857
858

    int vecSize = 0;
859
    SerUtil::deserialize(in, vecSize);
860
    data.clear();
861
862
863
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
864
      SerUtil::deserialize(in, dofIndex);
865
866
867
868
869
870
871
872
873

      TEST_EXIT_DBG(dofMap.count(dofIndex) != 0)
	("Dof index could not be deserialized correctly!\n");

      data[i] = dofMap[dofIndex];
    }
  }


874
  void MeshDistributor::serialize(std::ostream &out, RankToDofContainer &data)