ParallelDomainBase.cc 69.9 KB
Newer Older
Thomas Witkowski's avatar
Thomas Witkowski committed
1
#include <algorithm>
2
3
#include <iostream>
#include <fstream>
Thomas Witkowski's avatar
Thomas Witkowski committed
4
#include <boost/lexical_cast.hpp>
5
6
#include <boost/filesystem.hpp>

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

31
32
namespace AMDiS {

Thomas Witkowski's avatar
Thomas Witkowski committed
33
  using boost::lexical_cast;
34
  using namespace boost::filesystem;
Thomas Witkowski's avatar
Thomas Witkowski committed
35

36
37
38
39
40
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

41

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

61
62
63
64
65
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
66

67
  void MeshDistributor::initParallelization(AdaptInfo *adaptInfo)
68
  {
69
    FUNCNAME("MeshDistributor::initParallelization()");
70
71
72
73

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

74
75
    TEST_EXIT(mesh)("No mesh has been defined for mesh distribution!\n");

76
77
    // If the problem has been already read from a file, we do not need to do anything.
    if (deserialized)
78
      return;
79
    
80

81
82
83
84
85
    // 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();

86

87
88
89
90
91
92
93
    // create an initial partitioning of the mesh
    partitioner->createPartitionData();
    // set the element weights, which are 1 at the very first begin
    setElemWeights(adaptInfo);
    // and now partition the mesh
    partitionMesh(adaptInfo);   

94

Thomas Witkowski's avatar
Thomas Witkowski committed
95
#if (DEBUG != 0)
96
97
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
98
99
100
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
101

102
103
104
105
106
      if (writePartMesh > 0)
	writePartitioningMesh("part.vtu");
      else 
	MSG("Skip write part mesh!\n");
    }
107
108

    ParallelDomainDbg::testAllElements(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
109
#endif
110

111

112
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
113

114
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
115

116
117
118
119
#if (DEBUG != 0)
    ParallelDomainDbg::printBoundaryInfo(*this);
#endif

120

121
122
123
124
    // === Create new global and local DOF numbering. ===

    createLocalGlobalNumbering();

125

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
126
127
128
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
129
130
    macroElementStructureConsisten = true;

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
131

132
133
134
135
    // === Reset all DOFAdmins of the mesh. ===

    updateDofAdmins();

136

137
138
    // === If in debug mode, make some tests. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
139
#if (DEBUG != 0)
140
    MSG("AMDiS runs in debug mode, so make some test ...\n");
141
142
143
    debug::testSortedDofs(mesh, elMap);
    ParallelDomainDbg::testInteriorBoundary(*this);
    ParallelDomainDbg::testCommonDofs(*this, true);
144
    MSG("Debug mode tests finished!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
145

146
    debug::writeMesh(feSpace, -1, "macro_mesh");   
147
#endif
148

149

150
151
152
    // === Create periodic dof mapping, if there are periodic boundaries. ===

    createPeriodicMap();
153

154

155
    // === Global refinements. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
156

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

Thomas Witkowski's avatar
Thomas Witkowski committed
160
    if (globalRefinement > 0) {
161
      refineManager->globalRefine(mesh, globalRefinement);
162

163
#if (DEBUG != 0)
164
      debug::writeMesh(feSpace, -1, "gr_mesh");
165
166
#endif

167
      updateLocalGlobalNumbering();
168
      
169
      // === Update periodic mapping, if there are periodic boundaries. ===
170
      
171
      createPeriodicMap();
Thomas Witkowski's avatar
Thomas Witkowski committed
172
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
173

174

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

177
178
179
180
181
182
    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);
Thomas Witkowski's avatar
Thomas Witkowski committed
183

184
185
186
187
188
189
	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);
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
190
191
    }

192

Thomas Witkowski's avatar
Thomas Witkowski committed
193
194
195
    // === Remove periodic boundary conditions in sequential problem definition. ===

    // Remove periodic boundaries in boundary manager on matrices and vectors.
196
197
198
    for (unsigned int i = 0; i < probStat.size(); i++) {
      int nComponents = probStat[i]->getNumComponents();

Thomas Witkowski's avatar
Thomas Witkowski committed
199
      for (int j = 0; j < nComponents; j++) {
200
201
202
203
204
205
206
207
208
	for (int k = 0; k < nComponents; k++) {
	  DOFMatrix* mat = probStat[i]->getSystemMatrix(j, k);
	  if (mat && mat->getBoundaryManager())
	    removeBoundaryCondition(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
	}
	
	if (probStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager())
	  removeBoundaryCondition(const_cast<BoundaryIndexMap&>(probStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
	
209
	if (probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager())
210
	  removeBoundaryCondition(const_cast<BoundaryIndexMap&>(probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
Thomas Witkowski's avatar
Thomas Witkowski committed
211
212
213
214
215
216
217
218
219
220
      }
    }

    // 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);
    }    
221
222
  }

223

224
225
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
255
256
257
258
259
  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");
      TEST_EXIT(mesh->getDOFAdmin(0).getNumberOfPreDOFs(0) == 0)
	("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;
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    GET_PARAMETER(0, probVec->getName() + "->output->write serialization", "%d", 
		  &writeSerialization);
    if (writeSerialization && !writeSerializationFile) {
      std::string f = "";
      GET_PARAMETER(0, probVec->getName() + "->output->serialization filename", &f);
      path myPath(f);
      std::string meshFilename = 
	myPath.parent_path().directory_string() + "/meshDistributor.ser";


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

    int readSerialization = 0;
279
280
    GET_PARAMETER(0, probVec->getName() + "->input->read serialization", "%d", 
		  &readSerialization);
281
282
283
284
    if (readSerialization) {
      std::string filename = "";
      GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
      filename += ".p" + lexical_cast<std::string>(mpiRank);
285
      MSG("Start deserialization with %s\n", filename.c_str());
286
      std::ifstream in(filename.c_str());
287
      probVec->deserialize(in);
288
      in.close();
289
290
291
292
293
294
295
296
297
298
299
300
301
302
      MSG("Deserialization from file: %s\n", filename.c_str());

      if (!deserialized) {
	GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
	path myPath(filename);
	std::string meshFilename = 
	  myPath.parent_path().directory_string() + "/meshDistributor.ser.p" + 
	  lexical_cast<std::string>(mpiRank);
	std::ifstream in(meshFilename.c_str());
	deserialize(in);
	in.close();
	MSG("Deserializtion of mesh distributor from file: %s\n", meshFilename.c_str());
	deserialized = true;
      }
303
304
305
306
307
308
309
    }

    probStat.push_back(probVec);
  }


  void MeshDistributor::exitParallelization(AdaptInfo *adaptInfo)
310
  {}
311

312
  
313
  void MeshDistributor::updateDofAdmins()
314
  {
315
    FUNCNAME("MeshDistributor::updateDofAdmins()");
316
317

    for (int i = 0; i < mesh->getNumberOfDOFAdmin(); i++) {
318
      DOFAdmin& admin = const_cast<DOFAdmin&>(mesh->getDOFAdmin(i));
319
320
321

      // There must be always more allocated DOFs than used DOFs in DOFAdmin. Otherwise,
      // it is not possible to define a first DOF hole.
322
      if (static_cast<unsigned int>(admin.getSize()) == mapLocalGlobalDofs.size())
323
	admin.enlargeDOFLists();
324
325
326
      
      for (int j = 0; j < admin.getSize(); j++)
	admin.setDOFFree(j, true);
327
      for (unsigned int j = 0; j < mapLocalGlobalDofs.size(); j++)
328
329
 	admin.setDOFFree(j, false);

330
331
332
      admin.setUsedSize(mapLocalGlobalDofs.size());
      admin.setUsedCount(mapLocalGlobalDofs.size());
      admin.setFirstHole(mapLocalGlobalDofs.size());
333
334
335
    }
  }

336

337
  void MeshDistributor::testForMacroMesh()
338
  {
339
    FUNCNAME("MeshDistributor::testForMacroMesh()");
340
341
342
343
344
345
346

    int nMacroElements = 0;

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
    while (elInfo) {
      TEST_EXIT(elInfo->getLevel() == 0)
347
	("Mesh is already refined! This does not work with parallelization!\n");
348
349
350
351
352
353
354
355
356
357
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

358

359
  void MeshDistributor::synchVector(DOFVector<double> &vec)
360
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
361
    StdMpi<std::vector<double> > stdMpi(mpiComm);
362
363

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
364
	 sendIt != sendDofs.end(); ++sendIt) {
365
      std::vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
366
367
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
368
      
Thomas Witkowski's avatar
Thomas Witkowski committed
369
370
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
371
372
373
374

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

Thomas Witkowski's avatar
Thomas Witkowski committed
375
376
377
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
378

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

Thomas Witkowski's avatar
Thomas Witkowski committed
381
382
383
384
385
    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];
  }
386
387


388
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
389
  {
390
    int nComponents = vec.getSize();
Thomas Witkowski's avatar
Thomas Witkowski committed
391
392
393
394
395
396
397
398
399
400
401
402
    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])]);
403
404
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
405
      stdMpi.send(sendIt->first, dofs);
406
407
408
    }

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

Thomas Witkowski's avatar
Thomas Witkowski committed
412
    stdMpi.startCommunication<double>(MPI_DOUBLE);
413
414

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
415
416
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
417
418

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
419
420
421
422
423
      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++];
424
425
426
427
      }
    }
  }

428

429
  void MeshDistributor::removeBoundaryCondition(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
430
431
432
433
434
435
436
437
438
439
440
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


441
  void MeshDistributor::checkMeshChange()
442
  {
443
    FUNCNAME("MeshDistributor::checkMeshChange()");
444

445
446
447
448
#if (DEBUG != 0)
    debug::writeMesh(feSpace, -1, "before_check_mesh");
#endif

449
450
451
452
453
    // === 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);
454

455
    if (recvAllValues == 0)
456
457
      return;

458
459
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
460

461
462
463
464
465
    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.
466
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
467
468

      for (InteriorBoundary::iterator it(myIntBoundary); !it.end(); ++it)
469
	if (it->rankObj.subObj == EDGE || it->rankObj.subObj == FACE)
470
	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
471
472

      for (InteriorBoundary::iterator it(otherIntBoundary); !it.end(); ++it)
473
	if (it->rankObj.subObj == EDGE || it->rankObj.subObj == FACE)
474
	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
475

476

477
      // === Check the boundaries and adapt mesh if necessary. ===
478

479
480
481
482
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

483
484
485
486
487
488
489
      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);
490
491
492
493

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

496
497

#if (DEBUG != 0)
498
    debug::writeMesh(feSpace, -1, "mesh");
499
500
501
502
503
504
#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. ===
505

506
    mesh->dofCompress();
507
    updateLocalGlobalNumbering();
508
509
510
511

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

    createPeriodicMap();
512
513
514
  }

  
515
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
516
  {
517
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
518
519
520
521
522
523

    // === Create mesh structure codes for all ranks boundary elements. ===
       
    std::map<int, MeshCodeVec> sendCodes;
   
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
524
525
526
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
527
	elCode.init(boundIt->rankObj);
528
529
530
531
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
532
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
533
    stdMpi.send(sendCodes);
534
535
536
    stdMpi.recv(allBound);
    stdMpi.startCommunication<unsigned long int>(MPI_UNSIGNED_LONG);
 
537
    // === Compare received mesh structure codes. ===
538
    
539
540
    bool meshFitTogether = true;

541
542
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
      
543
544
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
545
      
546
547
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
548

549
550
551
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
	
552
553
	if (elCode.getCode() != recvCodes[i].getCode()) {
	  TEST_EXIT_DBG(refineManager)("Refinement manager is not set correctly!\n");
554
555

	  bool b = fitElementToMeshCode(recvCodes[i], 
556
					boundIt->rankObj.el,
557
					boundIt->rankObj.subObj,
558
					boundIt->rankObj.ithObj, 
559
560
					boundIt->rankObj.elType,
					boundIt->rankObj.reverseMode);  
561

562
563
	  if (b)
	    meshFitTogether = false;
564
	}
565
	
566
	i++;
567
568
569
      }
    }

570
    return meshFitTogether;
571
  }
572
573


574
  bool MeshDistributor::fitElementToMeshCode(MeshStructure &code, 
575
576
577
578
579
					     Element *el, 
					     GeoIndex subObj,
					     int ithObj, 
					     int elType,
					     bool reverseMode)
580
  {
581
    FUNCNAME("MeshDistributor::fitElementToMeshCode()");
582

583
584
    TEST_EXIT_DBG(el)("No element given!\n");

585
586
    if (code.empty())
      return false;
587
588
589

    int s1 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s2 = el->getSubObjOfChild(1, subObj, ithObj, elType);
590
591
592

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

593
    bool meshChanged = false;
594
595
596
597
598
599
600
    Flag traverseFlag = 
      Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND;

    if (reverseMode) {
      std::swap(s1, s2);
      traverseFlag |= Mesh::CALL_REVERSE_MODE;
    }
601
602

    if (s1 != -1 && s2 != -1) {
603
      TraverseStack stack;
604
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
605
606
607
608
      while (elInfo && elInfo->getElement() != el) {
	elInfo = stack.traverseNext(elInfo);
      }

609
      meshChanged = fitElementToMeshCode2(code, stack, subObj, ithObj, elType, reverseMode);
610
611
      return meshChanged;
    }
612
613

    if (el->isLeaf()) {
614
615
616
      if (code.getNumElements() == 1 && code.isLeafElement())
	return false;     

617
618
619
      meshChanged = true;

      TraverseStack stack;
620
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
621
622
623
624
625
626
627

      while (elInfo && elInfo->getElement() != el) {
	elInfo = stack.traverseNext(elInfo);
      }

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

628
      el->setMark(1);
629
630
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
631
      refineManager->refineFunction(elInfo);
632
    }
633

634
635
636
637
638
    Element *child0 = el->getFirstChild();
    Element *child1 = el->getSecondChild();
    if (reverseMode)
      std::swap(child0, child1);

639
    if (s1 != -1) {
640
      TraverseStack stack;
641
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
642

643
      while (elInfo && elInfo->getElement() != child0) {
644
645
646
	elInfo = stack.traverseNext(elInfo);
      }

647
      meshChanged |= 
648
	fitElementToMeshCode2(code, stack, subObj, s1, el->getChildType(elType), reverseMode);
649
    } else {
650
      TraverseStack stack;
651
      ElInfo *elInfo = stack.traverseFirst(el->getMesh(), -1, traverseFlag);
652

653
      while (elInfo && elInfo->getElement() != child1) {
654
655
656
	elInfo = stack.traverseNext(elInfo);
      }

657
      meshChanged |= 
658
	fitElementToMeshCode2(code, stack, subObj, s2, el->getChildType(elType), reverseMode);
659
660
661
    }

    return meshChanged;
662
663
  }

664

665
  bool MeshDistributor::fitElementToMeshCode2(MeshStructure &code, 
666
667
668
669
670
					      TraverseStack &stack,
					      GeoIndex subObj,
					      int ithObj, 
					      int elType,
					      bool reverseMode)
671
  {
672
    FUNCNAME("MeshDistributor::fitElementToMeshCode2()");
673

674
675
    ElInfo *elInfo = stack.getElInfo();

676
    bool value = false;
677
678
679
680
681
682
683
684
685
686
687
    if (!elInfo)
      return value;

    Element *el = elInfo->getElement();

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

      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getLevel() > level);
688
     
689
690
      return value;
    }
691

692
693
    if (!elInfo)
      return value;
694

695
    if (el->isLeaf()) {
696
      el->setMark(1);
697
698
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
699
      refineManager->refineFunction(elInfo);
700
701
702
      value = true;
    }

703
704
    int s1 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s2 = el->getSubObjOfChild(1, subObj, ithObj, elType);
705
706
707
708
709
710
    Element *child0 = el->getFirstChild();
    Element *child1 = el->getSecondChild();
    if (reverseMode) {
      std::swap(s1, s2);
      std::swap(child0, child1);
    }
711

712
    if (s1 != -1) {
713
      stack.traverseNext(elInfo);
714
      code.nextElement();
715
      value |= fitElementToMeshCode2(code, stack, subObj, s1, el->getChildType(elType), reverseMode);
716
717
718
719
      elInfo = stack.getElInfo();
    } else {
      do {
	elInfo = stack.traverseNext(elInfo);
720
      } while (elInfo && elInfo->getElement() != child1);      
721
722
    }  

723
    TEST_EXIT_DBG(elInfo->getElement() == child1)("This should not happen!\n");
724

725
    if (s2 != -1) {
726
      code.nextElement();
727
      value |= fitElementToMeshCode2(code, stack, subObj, s2, el->getChildType(elType), reverseMode);
728
729
    } else {
      int level = elInfo->getLevel();
730

731
732
733
734
      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getLevel() > level);
    }
735

736
737
738
    return value;
  }

739
  
740
  void MeshDistributor::serialize(std::ostream &out, DofContainer &data)
Thomas Witkowski's avatar
Thomas Witkowski committed
741
  {    
742
    int vecSize = data.size();
743
    SerUtil::serialize(out, vecSize);
744
745
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = (*data[i]);
746
      SerUtil::serialize(out, dofIndex);
747
748
749
750
    }
  }


751
  void MeshDistributor::deserialize(std::istream &in, DofContainer &data,
752
				    std::map<int, const DegreeOfFreedom*> &dofMap)
753
  {
754
    FUNCNAME("MeshDistributor::deserialize()");
755
756

    int vecSize = 0;
757
    SerUtil::deserialize(in, vecSize);
758
759
760
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
761
      SerUtil::deserialize(in, dofIndex);
762
763
764
765
766
767
768
769
770

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

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


771
  void MeshDistributor::serialize(std::ostream &out, RankToDofContainer &data)
772
773
  {
    int mapSize = data.size();
774
    SerUtil::serialize(out, mapSize);
775
776
    for (RankToDofContainer::iterator it = data.begin(); it != data.end(); ++it) {
      int rank = it->first;
777
      SerUtil::serialize(out, rank);
778
779
780
781
782
      serialize(out, it->second);
    }
  }

  
783
  void MeshDistributor::deserialize(std::istream &in, RankToDofContainer &data,
784
				    std::map<int, const DegreeOfFreedom*> &dofMap)
785
786
  {
    int mapSize = 0;
787
    SerUtil::deserialize(in, mapSize);
788
789
    for (int i = 0; i < mapSize; i++) {
      int rank = 0;
790
      SerUtil::deserialize(in, rank);
791
792
793
794
      deserialize(in, data[rank], dofMap);      
    }
  }

795

796
  double MeshDistributor::setElemWeights(AdaptInfo *adaptInfo) 
797
  {
798
    FUNCNAME("MeshDistributor::setElemWeights()");
799

800
    double localWeightSum = 0.0;
801
    elemWeights.clear();
802
803
804
805
806
807
808
809
810
811
812
813
814
815
      
    std::string filename = "";
    GET_PARAMETER(0, mesh->getName() + "->macro weights", &filename);
    if (filename != "") {
      MSG("Read macro weights from %s\n", filename.c_str());

      std::ifstream infile;
      infile.open(filename.c_str(), std::ifstream::in);
      while (!infile.eof()) {
	int elNum, elWeight;
	infile >> elNum;
	if (infile.eof())
	  break;
	infile >> elWeight;
816

817
818
819
	elemWeights[elNum] = elWeight;
	localWeightSum += elWeight;
      }
820

821
      infile.close();
822
    } else {           
823
      TraverseStack stack;
824
      ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
825
      while (elInfo) {
826
827
828
	elemWeights[elInfo->getElement()->getIndex()] = 1.0;
	localWeightSum++;

829
	elInfo = stack.traverseNext(elInfo);
830
831
832
833
834
835
      }
    }

    return localWeightSum;
  }

836

837
  void MeshDistributor::partitionMesh(AdaptInfo *adaptInfo)
838
  {
839
    FUNCNAME("MeshDistributor::partitionMesh()");
840

841
842
843
844
845
846
847
848
849
850
851
852
    if (initialPartitionMesh) {
      initialPartitionMesh = false;
      partitioner->fillCoarsePartitionVec(&oldPartitionVec);
      partitioner->partition(&elemWeights, INITIAL);
    } else {
      oldPartitionVec = partitionVec;
      partitioner->partition(&elemWeights, ADAPTIVE_REPART, 100.0 /*0.000001*/);
    }    

    partitioner->fillCoarsePartitionVec(&partitionVec);
  }

853

854
  void MeshDistributor::createInteriorBoundaryInfo()
855
  {
856
    FUNCNAME("MeshDistributor::createInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
857

Thomas Witkowski's avatar
Thomas Witkowski committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
    // === First, create the interior boundaries based on macro element's  ===
    // === neighbour informations.                                         ===

    createMacroElementInteriorBoundaryInfo();

    // === Second, search the whole mesh for interior boundaries that consists of ===
    // === substructures of the macro elements.                                   ===

    createSubstructureInteriorBoundaryInfo();


    // === Once we have this information, we must care about the order of the atomic ===
    // === bounds in the three boundary handling object. Eventually all the bound-   ===
    // === aries have to be in the same order on both ranks that share the bounday.  ===

    StdMpi<std::vector<AtomicBoundary> > stdMpi(mpiComm);
    stdMpi.send(myIntBoundary.boundary);
    stdMpi.recv(otherIntBoundary.boundary);
    stdMpi.startCommunication<int>(MPI_INT);
877

Thomas Witkowski's avatar
Thomas Witkowski committed
878
879
880
881
882
883
884
885
    // === The information about all neighbouring boundaries has been received. So ===
    // === the rank tests if its own atomic boundaries are in the same order. If   ===
    // === not, the atomic boundaries are swaped to the correct order.             ===

    for (RankToBoundMap::iterator rankIt = otherIntBoundary.boundary.begin();
	 rankIt != otherIntBoundary.boundary.end(); ++rankIt) {

      // === We have received from rank "rankIt->first" the ordered list of element ===
886
      // === indices. Now, we have to sort the corresponding list in this rank to   ===
Thomas Witkowski's avatar
Thomas Witkowski committed
887
      // === get the same order.                                                    ===
888
     
Thomas Witkowski's avatar
Thomas Witkowski committed
889
      for (int j = 0; j < static_cast<int>(rankIt->second.size()); j++) {
890

Thomas Witkowski's avatar
Thomas Witkowski committed
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
	// If the expected object is not at place, search for it.

	BoundaryObject &recvedBound = stdMpi.getRecvData()[rankIt->first][j].rankObj;

	if ((rankIt->second)[j].neighObj != recvedBound) {
	  int k = j + 1;
	  for (; k < static_cast<int>(rankIt->second.size()); k++)
 	    if ((rankIt->second)[k].neighObj == recvedBound)
	      break;

	  // The element must always be found, because the list is just in another order.
	  TEST_EXIT_DBG(k < static_cast<int>(rankIt->second.size()))
	    ("Should never happen!\n");

	  // Swap the current with the found element.
	  AtomicBoundary tmpBound = (rankIt->second)[k];
	  (rankIt->second)[k] = (rankIt->second)[j];
	  (rankIt->second)[j] = tmpBound;	
	}
      }
    }

    // === Do the same for the periodic boundaries. ===

    if (periodicBoundary.boundary.size() > 0) {
      stdMpi.clear();

      InteriorBoundary sendBounds, recvBounds;     
      for (RankToBoundMap::iterator rankIt = periodicBoundary.boundary.begin();
	   rankIt != periodicBoundary.boundary.end(); ++rankIt) {

	TEST_EXIT_DBG(rankIt->first != mpiRank)
	  ("It is no possible to have an interior boundary within a rank partition!\n");

	if (rankIt->first < mpiRank)
	  sendBounds.boundary[rankIt->first] = rankIt->second;
	else
	  recvBounds.boundary[rankIt->first] = rankIt->second;
      }

      stdMpi.send(sendBounds.boundary);
      stdMpi.recv(recvBounds.boundary);
      stdMpi.startCommunication<int>(MPI_INT);

      for (RankToBoundMap::iterator rankIt = periodicBoundary.boundary.begin();
	   rankIt != periodicBoundary.boundary.end(); ++rankIt) {
	if (rankIt->first <= mpiRank)
	  continue;
	  
	for (int j = 0; j < static_cast<int>(rankIt->second.size()); j++) {
	  
	  BoundaryObject &recvedBound = stdMpi.getRecvData()[rankIt->first][j].rankObj;
	  
	  if (periodicBoundary.boundary[rankIt->first][j].neighObj != recvedBound) {    
	    int k = j + 1;	    
	    for (; k < static_cast<int>(rankIt->second.size()); k++)
	      if (periodicBoundary.boundary[rankIt->first][k].neighObj == recvedBound)
		break;
	    
	    // The element must always be found, because the list is just in 
	    // another order.
	    TEST_EXIT_DBG(k < static_cast<int>(rankIt->second.size()))
	      ("Should never happen!\n");
	    
	    // Swap the current with the found element.
	    AtomicBoundary tmpBound = (rankIt->second)[k];
	    (rankIt->second)[k] = (rankIt->second)[j];
	    (rankIt->second)[j] = tmpBound;	
	  }  	  
	}
      }     
    } // periodicBoundary.boundary.size() > 0
  }


966
  void MeshDistributor::createMacroElementInteriorBoundaryInfo()
Thomas Witkowski's avatar
Thomas Witkowski committed
967
  {
968
    FUNCNAME("MeshDistributor::createMacroElementInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
969

970
971
    int nNeighbours = mesh->getGeo(NEIGH);
    int dim = mesh->getDim();
972
    GeoIndex subObj = INDEX_OF_DIM(dim - 1, dim);