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

29
30
namespace AMDiS {

Thomas Witkowski's avatar
Thomas Witkowski committed
31
32
  using boost::lexical_cast;

33
34
35
36
37
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

38

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

56
57
58
59
60
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
61

62
  void MeshDistributor::initParallelization(AdaptInfo *adaptInfo)
63
  {
64
    FUNCNAME("MeshDistributor::initParallelization()");
65
66
67
68

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

69
70
    TEST_EXIT(mesh)("No mesh has been defined for mesh distribution!\n");

71
72
    // If the problem has been already read from a file, we do not need to do anything.
    if (deserialized)
73
74
      return;

75
76
77
78
79
    // 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();

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

Thomas Witkowski's avatar
Thomas Witkowski committed
87
#if (DEBUG != 0)
88
89
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
90
91
92
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
93

94
95
96
97
98
      if (writePartMesh > 0)
	writePartitioningMesh("part.vtu");
      else 
	MSG("Skip write part mesh!\n");
    }
99
100

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

103
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
104

105
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
106

107
108
109
110
#if (DEBUG != 0)
    ParallelDomainDbg::printBoundaryInfo(*this);
#endif

111
112
113
114
    // === Create new global and local DOF numbering. ===

    createLocalGlobalNumbering();

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
115
116
117
118
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();

119
120
121
122
    // === Reset all DOFAdmins of the mesh. ===

    updateDofAdmins();

123
124
    // === If in debug mode, make some tests. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
125
#if (DEBUG != 0)
126
    MSG("AMDiS runs in debug mode, so make some test ...\n");
127
128
129
    debug::testSortedDofs(mesh, elMap);
    ParallelDomainDbg::testInteriorBoundary(*this);
    ParallelDomainDbg::testCommonDofs(*this, true);
130
    MSG("Debug mode tests finished!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
131

132
    debug::writeMesh(feSpace, -1, "macro_mesh");   
133
#endif
134

135
136
137
    // === Create periodic dof mapping, if there are periodic boundaries. ===

    createPeriodicMap();
138

139
    // === Global refinements. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
140

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

Thomas Witkowski's avatar
Thomas Witkowski committed
144
    if (globalRefinement > 0) {
145
      refineManager->globalRefine(mesh, globalRefinement);
146

147
#if (DEBUG != 0)
148
      debug::writeMesh(feSpace, -1, "gr_mesh");
149
150
#endif

151
      updateLocalGlobalNumbering();
152
      
153
      // === Update periodic mapping, if there are periodic boundaries. ===
154
      
155
      createPeriodicMap();
Thomas Witkowski's avatar
Thomas Witkowski committed
156
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
157
158
159

    /// === Set DOF rank information to all matrices and vectors. ===

160
161
162
163
164
165
    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
166

167
168
169
170
171
172
	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
173
174
    }

175

Thomas Witkowski's avatar
Thomas Witkowski committed
176
177
178
    // === Remove periodic boundary conditions in sequential problem definition. ===

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

Thomas Witkowski's avatar
Thomas Witkowski committed
182
      for (int j = 0; j < nComponents; j++) {
183
184
185
186
187
188
189
190
191
192
193
	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()));
	
	if (probStat[i]->getRhs()->getDOFVector(i)->getBoundaryManager())
	  removeBoundaryCondition(const_cast<BoundaryIndexMap&>(probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
Thomas Witkowski's avatar
Thomas Witkowski committed
194
195
196
197
198
199
200
201
202
203
      }
    }

    // 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);
    }    
204
205
  }

206

207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
260
261
262
263
264
265
266
  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;
    GET_PARAMETER(0, probVec->getName() + "->output->write serialization", "%d", &writeSerialization);
    if (writeSerialization)
      probVec->getFileWriterList().push_back(new Serializer<MeshDistributor>(this));

    int readSerialization = 0;
    GET_PARAMETER(0, probVec->getName() + "->input->read serialization", "%d", &readSerialization);
    if (readSerialization) {
      ERROR_EXIT("Must be reimplemented!\n");
#if 0      
      std::string filename = "";
      GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
      filename += ".p" + lexical_cast<std::string>(mpiRank);
      MSG("Start serialization with %s\n", filename.c_str());
      std::ifstream in(filename.c_str());
      deserialize(in);
      in.close();
#endif
    }

    probStat.push_back(probVec);
  }


  void MeshDistributor::exitParallelization(AdaptInfo *adaptInfo)
267
  {}
268

269
  
270
  void MeshDistributor::updateDofAdmins()
271
  {
272
    FUNCNAME("MeshDistributor::updateDofAdmins()");
273
274

    for (int i = 0; i < mesh->getNumberOfDOFAdmin(); i++) {
275
      DOFAdmin& admin = const_cast<DOFAdmin&>(mesh->getDOFAdmin(i));
276
277
278

      // There must be always more allocated DOFs than used DOFs in DOFAdmin. Otherwise,
      // it is not possible to define a first DOF hole.
279
      if (static_cast<unsigned int>(admin.getSize()) == mapLocalGlobalDofs.size())
280
	admin.enlargeDOFLists();
281
282
283
      
      for (int j = 0; j < admin.getSize(); j++)
	admin.setDOFFree(j, true);
284
      for (unsigned int j = 0; j < mapLocalGlobalDofs.size(); j++)
285
286
 	admin.setDOFFree(j, false);

287
288
289
      admin.setUsedSize(mapLocalGlobalDofs.size());
      admin.setUsedCount(mapLocalGlobalDofs.size());
      admin.setFirstHole(mapLocalGlobalDofs.size());
290
291
292
    }
  }

293

294
  void MeshDistributor::testForMacroMesh()
295
  {
296
    FUNCNAME("MeshDistributor::testForMacroMesh()");
297
298
299
300
301
302
303

    int nMacroElements = 0;

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
    while (elInfo) {
      TEST_EXIT(elInfo->getLevel() == 0)
304
	("Mesh is already refined! This does not work with parallelization!\n");
305
306
307
308
309
310
311
312
313
314
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

315

316
  void MeshDistributor::synchVector(DOFVector<double> &vec)
317
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
318
    StdMpi<std::vector<double> > stdMpi(mpiComm);
319
320

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
321
	 sendIt != sendDofs.end(); ++sendIt) {
322
      std::vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
323
324
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
325
      
Thomas Witkowski's avatar
Thomas Witkowski committed
326
327
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
328
329
330
331

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

Thomas Witkowski's avatar
Thomas Witkowski committed
332
333
334
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
335

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

Thomas Witkowski's avatar
Thomas Witkowski committed
338
339
340
341
342
    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];
  }
343
344


345
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
346
  {
347
    int nComponents = vec.getSize();
Thomas Witkowski's avatar
Thomas Witkowski committed
348
349
350
351
352
353
354
355
356
357
358
359
    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])]);
360
361
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
362
      stdMpi.send(sendIt->first, dofs);
363
364
365
    }

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

Thomas Witkowski's avatar
Thomas Witkowski committed
369
    stdMpi.startCommunication<double>(MPI_DOUBLE);
370
371

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
372
373
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
374
375

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
376
377
378
379
380
      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++];
381
382
383
384
      }
    }
  }

385

386
  void MeshDistributor::removeBoundaryCondition(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
387
388
389
390
391
392
393
394
395
396
397
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


398
  void MeshDistributor::checkMeshChange()
399
  {
400
    FUNCNAME("MeshDistributor::checkMeshChange()");
401

402
403
404
405
406
    // === 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);
407

408
    if (recvAllValues == 0)
409
410
      return;

411
412
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
413

414
415
416
417
418
    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.
419
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
420
421

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

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

429

430
      // === Check the boundaries and adapt mesh if necessary. ===
431

432
433
434
435
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

436
437
438
439
440
441
442
      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);
443
444
445
446

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

449
450

#if (DEBUG != 0)
451
    debug::writeMesh(feSpace, -1, "mesh");
452
453
454
455
456
457
#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. ===
458

459
460
461
462
    updateLocalGlobalNumbering();
  }

  
463
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
464
  {
465
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
466
467
468
469
470
471

    // === Create mesh structure codes for all ranks boundary elements. ===
       
    std::map<int, MeshCodeVec> sendCodes;
   
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
472
473
474
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
475
	elCode.init(boundIt->rankObj);
476
477
478
479
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
480
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
481
    stdMpi.send(sendCodes);
482
483
484
    stdMpi.recv(allBound);
    stdMpi.startCommunication<unsigned long int>(MPI_UNSIGNED_LONG);
 
485
    // === Compare received mesh structure codes. ===
486
    
487
488
    bool meshFitTogether = true;

489
490
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
      
491
492
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
493
      
494
495
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
496

497
498
499
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
	
500
501
	if (elCode.getCode() != recvCodes[i].getCode()) {
	  TEST_EXIT_DBG(refineManager)("Refinement manager is not set correctly!\n");
502
503

	  bool b = fitElementToMeshCode(recvCodes[i], 
504
					boundIt->rankObj.el,
505
					boundIt->rankObj.subObj,
506
					boundIt->rankObj.ithObj, 
507
					boundIt->rankObj.elType);  
508

509
510
	  if (b)
	    meshFitTogether = false;
511
	}
512
	
513
	i++;
514
515
516
      }
    }

517
    return meshFitTogether;
518
  }
519
520


521
  bool MeshDistributor::fitElementToMeshCode(MeshStructure &code, 
522
						Element *el, 
523
524
						GeoIndex subObj,
						int ithObj, 
525
						int elType)
526
  {
527
    FUNCNAME("MeshDistributor::fitElementToMeshCode()");
528

529
530
    TEST_EXIT_DBG(el)("No element given!\n");

531
532
    if (code.empty())
      return false;
533
534
535

    int s1 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s2 = el->getSubObjOfChild(1, subObj, ithObj, elType);
536
537
538

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

539
540
541
    bool meshChanged = false;

    if (s1 != -1 && s2 != -1) {
542
543
544
545
546
547
548
      TraverseStack stack;
      ElInfo *elInfo = 
	stack.traverseFirst(el->getMesh(), -1, Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);
      while (elInfo && elInfo->getElement() != el) {
	elInfo = stack.traverseNext(elInfo);
      }

549
      meshChanged = fitElementToMeshCode2(code, stack, subObj, ithObj, elType);
550
551
      return meshChanged;
    }
552
553

    if (el->isLeaf()) {
554
555
556
      if (code.getNumElements() == 1 && code.isLeafElement())
	return false;     

557
558
559
560
561
562
563
564
565
566
567
568
      meshChanged = true;

      TraverseStack stack;
      ElInfo *elInfo = 
	stack.traverseFirst(el->getMesh(), -1, Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);

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

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

569
      el->setMark(1);
570
571
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
572
      refineManager->refineFunction(elInfo);
573
    }
574
575

    if (s1 != -1) {
576
577
578
579
580
581
582
583
      TraverseStack stack;
      ElInfo *elInfo = 
	stack.traverseFirst(el->getMesh(), -1, Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);

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

584
585
      meshChanged |= 
	fitElementToMeshCode2(code, stack, subObj, s1, el->getChildType(elType));
586
    } else {
587
588
589
590
591
592
593
594
      TraverseStack stack;
      ElInfo *elInfo = 
	stack.traverseFirst(el->getMesh(), -1, Mesh::CALL_EVERY_EL_PREORDER | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);

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

595
596
      meshChanged |= 
	fitElementToMeshCode2(code, stack, subObj, s2, el->getChildType(elType));
597
598
599
    }

    return meshChanged;
600
601
  }

602

603
  bool MeshDistributor::fitElementToMeshCode2(MeshStructure &code, 
604
						 TraverseStack &stack,
605
606
						 GeoIndex subObj,
						 int ithObj, 
607
						 int elType)
608
  {
609
    FUNCNAME("MeshDistributor::fitElementToMeshCode2()");
610

611
612
    ElInfo *elInfo = stack.getElInfo();

613
    bool value = false;
614
615
616
617
618
619
620
621
622
623
624
    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);
625
     
626
627
      return value;
    }
628

629
630
    if (!elInfo)
      return value;
631

632
    if (el->isLeaf()) {
633
      el->setMark(1);
634
635
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
636
      refineManager->refineFunction(elInfo);
637
638
639
      value = true;
    }

640
641
    int s1 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s2 = el->getSubObjOfChild(1, subObj, ithObj, elType);
642

643
    if (s1 != -1) {
644
      stack.traverseNext(elInfo);
645
      code.nextElement();
646
      value |= fitElementToMeshCode2(code, stack, subObj, s1, el->getChildType(elType));
647
648
649
650
651
      elInfo = stack.getElInfo();
    } else {
      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getElement() != el->getSecondChild());      
652
653
    }  

654
655
656
    TEST_EXIT_DBG(elInfo->getElement() == el->getSecondChild())
      ("This should not happen!\n");

657
    if (s2 != -1) {
658
      code.nextElement();
659
      value |= fitElementToMeshCode2(code, stack, subObj, s2, el->getChildType(elType));
660
661
    } else {
      int level = elInfo->getLevel();
662

663
664
665
666
      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getLevel() > level);
    }
667

668
669
670
    return value;
  }

671
  
672
  void MeshDistributor::serialize(std::ostream &out, DofContainer &data)
Thomas Witkowski's avatar
Thomas Witkowski committed
673
  {    
674
    int vecSize = data.size();
675
    SerUtil::serialize(out, vecSize);
676
677
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = (*data[i]);
678
      SerUtil::serialize(out, dofIndex);
679
680
681
682
    }
  }


683
  void MeshDistributor::deserialize(std::istream &in, DofContainer &data,
684
685
				       std::map<int, const DegreeOfFreedom*> &dofMap)
  {
686
    FUNCNAME("MeshDistributor::deserialize()");
687
688

    int vecSize = 0;
689
    SerUtil::deserialize(in, vecSize);
690
691
692
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
693
      SerUtil::deserialize(in, dofIndex);
694
695
696
697
698
699
700
701
702

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

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


703
  void MeshDistributor::serialize(std::ostream &out, RankToDofContainer &data)
704
705
  {
    int mapSize = data.size();
706
    SerUtil::serialize(out, mapSize);
707
708
    for (RankToDofContainer::iterator it = data.begin(); it != data.end(); ++it) {
      int rank = it->first;
709
      SerUtil::serialize(out, rank);
710
711
712
713
714
      serialize(out, it->second);
    }
  }

  
715
  void MeshDistributor::deserialize(std::istream &in, RankToDofContainer &data,
716
717
718
				       std::map<int, const DegreeOfFreedom*> &dofMap)
  {
    int mapSize = 0;
719
    SerUtil::deserialize(in, mapSize);
720
721
    for (int i = 0; i < mapSize; i++) {
      int rank = 0;
722
      SerUtil::deserialize(in, rank);
723
724
725
726
      deserialize(in, data[rank], dofMap);      
    }
  }

727

728
  double MeshDistributor::setElemWeights(AdaptInfo *adaptInfo) 
729
  {
730
    FUNCNAME("MeshDistributor::setElemWeights()");
731

732
    double localWeightSum = 0.0;
733
    elemWeights.clear();
734
735
736
737
738
739
740
741
742
743
744
745
746
747
      
    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;
748

749
750
751
	elemWeights[elNum] = elWeight;
	localWeightSum += elWeight;
      }
752

753
      infile.close();
754
    } else {           
755
      TraverseStack stack;
756
      ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
757
      while (elInfo) {
758
759
760
	elemWeights[elInfo->getElement()->getIndex()] = 1.0;
	localWeightSum++;

761
	elInfo = stack.traverseNext(elInfo);
762
763
764
765
766
767
      }
    }

    return localWeightSum;
  }

768

769
  void MeshDistributor::partitionMesh(AdaptInfo *adaptInfo)
770
  {
771
    FUNCNAME("MeshDistributor::partitionMesh()");
772

773
774
775
776
777
778
779
780
781
782
783
784
    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);
  }

785

786
  void MeshDistributor::createInteriorBoundaryInfo()
787
  {
788
    FUNCNAME("MeshDistributor::createInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
789

Thomas Witkowski's avatar
Thomas Witkowski committed
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    // === 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);
809

Thomas Witkowski's avatar
Thomas Witkowski committed
810
811
812
813
814
815
816
817
    // === 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 ===
818
      // === indices. Now, we have to sort the corresponding list in this rank to   ===
Thomas Witkowski's avatar
Thomas Witkowski committed
819
      // === get the same order.                                                    ===
820
     
Thomas Witkowski's avatar
Thomas Witkowski committed
821
      for (int j = 0; j < static_cast<int>(rankIt->second.size()); j++) {
822

Thomas Witkowski's avatar
Thomas Witkowski committed
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
	// 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
  }


898
  void MeshDistributor::createMacroElementInteriorBoundaryInfo()
Thomas Witkowski's avatar
Thomas Witkowski committed
899
  {
900
    FUNCNAME("MeshDistributor::createMacroElementInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
901

902
903
    int nNeighbours = mesh->getGeo(NEIGH);
    int dim = mesh->getDim();
904
    GeoIndex subObj = INDEX_OF_DIM(dim - 1, dim);
905
906
907

    // === First, traverse the mesh and search for all elements that have an  ===
    // === boundary with an element within another partition.                 ===
Thomas Witkowski's avatar
Thomas Witkowski committed
908

909
    TraverseStack stack;
910
911
912
    ElInfo *elInfo = 
      stack.traverseFirst(mesh, -1, 
			  Mesh::CALL_LEAF_EL | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);
913
914
915
    while (elInfo) {
      Element *element = elInfo->getElement();
      PartitionElementData *partitionData = 
916
	dynamic_cast<PartitionElementData*>(element->getElementData(PARTITION_ED));
917

918
      // Check, if the element is within rank's partition.
919
      if (partitionData->getPartitionStatus() == IN) {
920
	for (int i = 0; i < nNeighbours; i++) {
921
922
923
924
	  if (!elInfo->getNeighbour(i))
	    continue;

	  PartitionElementData *neighbourPartitionData =
925
926
	    dynamic_cast<PartitionElementData*>(elInfo->getNeighbour(i)->
						getElementData(PARTITION_ED));
927

928
 	  if (neighbourPartitionData->getPartitionStatus() == OUT) {
Thomas Witkowski's avatar
Thomas Witkowski committed
929

930
931
932
933
934
	    // We have found an element that is in rank's partition, but has a 
	    // neighbour outside of the rank's partition.

	    // === Create information about the boundary between the two elements. ===

935
	    AtomicBoundary bound;	    	    
936
937
	    bound.rankObj.el = element;
	    bound.rankObj.elIndex = element->getIndex();
938
	    bound.rankObj.elType = elInfo->getType();
939
	    bound.rankObj.subObj = subObj;
940
	    bound.rankObj.ithObj = i;
941
942

	    bound.neighObj.el = elInfo->getNeighbour(i);
943
	    bound.neighObj.elIndex = elInfo->getNeighbour(i)->getIndex();
944
	    bound.neighObj.elType = -1;
945
	    bound.neighObj.subObj = subObj;
946
	    bound.neighObj.ithObj = elInfo->getSideOfNeighbour(i);
947
	    
948
	    // Get rank number of the neighbouring element.
949
950
	    int otherElementRank = partitionVec[elInfo->getNeighbour(i)->getIndex()];

951
952
953
954
955
956
957
958
	    // === Add the boundary information object to the corresponding overall ===
	    // === boundary. There are three possibilities: if the boundary is a    ===
	    // === periodic boundary, just add it to \ref periodicBounadry. Here it ===
	    // === does not matter which rank is responsible for this boundary.     ===
	    // === Otherwise, the boundary is added either to \ref myIntBoundary or ===
	    // === to \ref otherIntBoundary. It dependes on which rank is respon-   ===
	    // === sible for this boundary.                                         ===

959
	    if (BoundaryManager::isBoundaryPeriodic(elInfo->getBoundary(subObj, i))) {	      
960
961
962
963
964
	      // We have found an element that is at an interior, periodic boundary.
	      AtomicBoundary& b = periodicBoundary.getNewAtomic(otherElementRank);
	      b = bound;
	    } else {
	      // We have found an element that is at an interior, non-periodic boundary.
965
966
967
968
969
970
971
972
973
	      if (mpiRank > otherElementRank) {
		AtomicBoundary& b = myIntBoundary.getNewAtomic(otherElementRank);
		b = bound;
		b.rankObj.setReverseMode(b.neighObj, feSpace);
	      } else {
		AtomicBoundary& b = otherIntBoundary.getNewAtomic(otherElementRank);
		b = bound;	 
		b.neighObj.setReverseMode(b.rankObj, feSpace);
	      }	      
974
	    }
975
976
977
978
979
980
 	  }
	}
      }

      elInfo = stack.traverseNext(elInfo);
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
981
  }
Thomas Witkowski's avatar
Thomas Witkowski committed
982
983


984
  void MeshDistributor::createSubstructureInteriorBoundaryInfo()
Thomas Witkowski's avatar
Thomas Witkowski committed
985
  {
986
    FUNCNAME("MeshDistributor::createSubstructureInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
987

988
989
990
    // === Seach for all vertices/edges, which are part of an interior boundary,  ===
    // === but are not part of the interior boundaries that are created based on  ===
    // === the information of macro elements.                                     ===
Thomas Witkowski's avatar
Thomas Witkowski committed
991
992

    int dim = mesh->getDim();
993
    const BasisFunction *basFcts = feSpace->getBasisFcts();
994
    std::vector<DegreeOfFreedom> localIndices(basFcts->getNumber());
Thomas Witkowski's avatar
Thomas Witkowski committed
995
996
997

    // Maps each DOF in the whole domain to the rank that ownes this DOF.
    std::map<DegreeOfFreedom, int> dofOwner;
998
    // Maps each DOF in ranks partition to the element object that contains this DOF.
Thomas Witkowski's avatar
Thomas Witkowski committed
999
    std::map<DegreeOfFreedom, BoundaryObject> rankDofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
1000

1001
1002
    // Maps each edge in the whole domain to the rank that ownes this edge.
    std::map<GlobalEdge, int> edgeOwner;
1003
    // Maps each edge in ranks partition to the element object that contains this edge.