ParallelDomainBase.cc 67.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
#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

Thomas Witkowski's avatar
Thomas Witkowski committed
39
40
41
42
43
44
45
46
47
48
  ParallelDomainBase::ParallelDomainBase(ProblemVec *problemStat,
					 ProblemInstatVec *problemInstat)
    : iterationIF(problemStat),
      timeIF(problemInstat),
      probStat(problemStat),
      name(problemStat->getName()),
      feSpace(problemStat->getFESpace(0)),
      mesh(feSpace->getMesh()),
      refineManager(problemStat->getRefinementManager(0)),
      info(problemStat->getInfo()),
49
      initialPartitionMesh(true),
50
      nRankDofs(0),
51
      rstart(0),
Thomas Witkowski's avatar
Thomas Witkowski committed
52
      nComponents(problemStat->getNumComponents()),
53
54
      deserialized(false),
      lastMeshChangeIndex(0)
55
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
56
57
58
59
60
61
62
    FUNCNAME("ParallelDomainBase::ParalleDomainBase()");

    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");

63
64
65
66
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
    partitioner = new ParMetisPartitioner(mesh, &mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

    // Test if all fe spaces are equal. Yet, different fe spaces are not supported for
    // domain parallelization.
    const FiniteElemSpace *fe = probStat->getFESpace(0);
    for (int i = 0; i < nComponents; i++)
      TEST_EXIT(fe == probStat->getFESpace(i))
	("Parallelization does not supported different FE spaces!\n");

    // Create parallel serialization file writer, if needed.
    int writeSerialization = 0;
    GET_PARAMETER(0, name + "->output->write serialization", "%d", &writeSerialization);
    if (writeSerialization)
      probStat->getFileWriterList().push_back(new Serializer<ParallelDomainBase>(this));

    int readSerialization = 0;
    GET_PARAMETER(0, name + "->input->read serialization", "%d", &readSerialization);
    if (readSerialization) {
      std::string filename = "";
      GET_PARAMETER(0, name + "->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();
    }
92
93
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
94

95
  void ParallelDomainBase::initParallelization(AdaptInfo *adaptInfo)
96
  {
97
98
99
100
101
102
103
    FUNCNAME("ParallelDomainBase::initParallelization()");

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

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

106
107
108
109
110
    // 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();

111
112
113
114
115
116
117
    // 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
118
#if (DEBUG != 0)
119
120
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
121
122
123
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
124

125
126
127
128
129
      if (writePartMesh > 0)
	writePartitioningMesh("part.vtu");
      else 
	MSG("Skip write part mesh!\n");
    }
130
131

    ParallelDomainDbg::testAllElements(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
132
#endif
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
139
140
141
#if (DEBUG != 0)
    ParallelDomainDbg::printBoundaryInfo(*this);
#endif

142
143
144
145
    // === Create new global and local DOF numbering. ===

    createLocalGlobalNumbering();

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
146
147
148
149
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();

150
151
152
153
    // === Reset all DOFAdmins of the mesh. ===

    updateDofAdmins();

154
155
    // === If in debug mode, make some tests. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
156
#if (DEBUG != 0)
157
    MSG("AMDiS runs in debug mode, so make some test ...\n");
158
159
160
    debug::testSortedDofs(mesh, elMap);
    ParallelDomainDbg::testInteriorBoundary(*this);
    ParallelDomainDbg::testCommonDofs(*this, true);
161
    MSG("Debug mode tests finished!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
162

163
    debug::writeMesh(feSpace, -1, "macro_mesh");   
164
#endif
165

166
167
168
    // === Create periodic dof mapping, if there are periodic boundaries. ===

    createPeriodicMap();
169

170
    // === Global refinements. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
171

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

Thomas Witkowski's avatar
Thomas Witkowski committed
175
    if (globalRefinement > 0) {
176
      refineManager->globalRefine(mesh, globalRefinement);
177

178
#if (DEBUG != 0)
179
      debug::writeMesh(feSpace, -1, "gr_mesh");
180
181
#endif

182
      updateLocalGlobalNumbering();
183
      
184
      // === Update periodic mapping, if there are periodic boundaries. ===
185
      
186
      createPeriodicMap();
Thomas Witkowski's avatar
Thomas Witkowski committed
187
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

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

    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++)
 	if (probStat->getSystemMatrix(i, j))
 	  probStat->getSystemMatrix(i, j)->setRankDofs(isRankDof);      

      TEST_EXIT_DBG(probStat->getRHS()->getDOFVector(i))("No rhs vector!\n");
      TEST_EXIT_DBG(probStat->getSolution()->getDOFVector(i))("No solution vector!\n");

      probStat->getRHS()->getDOFVector(i)->setRankDofs(isRankDof);
      probStat->getSolution()->getDOFVector(i)->setRankDofs(isRankDof);
    }

    // === Remove periodic boundary conditions in sequential problem definition. ===

    // Remove periodic boundaries in boundary manager on matrices and vectors.
    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++) {
	DOFMatrix* mat = probStat->getSystemMatrix(i, j);
 	if (mat && mat->getBoundaryManager())
	  removeBoundaryCondition(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
      }

      if (probStat->getSolution()->getDOFVector(i)->getBoundaryManager())
	removeBoundaryCondition(const_cast<BoundaryIndexMap&>(probStat->getSolution()->getDOFVector(i)->getBoundaryManager()->getBoundaryConditionMap()));

      if (probStat->getRHS()->getDOFVector(i)->getBoundaryManager())
	removeBoundaryCondition(const_cast<BoundaryIndexMap&>(probStat->getRHS()->getDOFVector(i)->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);
    }    
227
228
  }

229
230

  void ParallelDomainBase::exitParallelization(AdaptInfo *adaptInfo)
231
  {}
232

233
234
235
  
  void ParallelDomainBase::updateDofAdmins()
  {
236
237
238
    FUNCNAME("ParallelDomainBase::updateDofAdmins()");

    for (int i = 0; i < mesh->getNumberOfDOFAdmin(); i++) {
239
      DOFAdmin& admin = const_cast<DOFAdmin&>(mesh->getDOFAdmin(i));
240
241
242

      // There must be always more allocated DOFs than used DOFs in DOFAdmin. Otherwise,
      // it is not possible to define a first DOF hole.
243
      if (static_cast<unsigned int>(admin.getSize()) == mapLocalGlobalDofs.size())
244
	admin.enlargeDOFLists();
245
246
247
      
      for (int j = 0; j < admin.getSize(); j++)
	admin.setDOFFree(j, true);
248
      for (unsigned int j = 0; j < mapLocalGlobalDofs.size(); j++)
249
250
 	admin.setDOFFree(j, false);

251
252
253
      admin.setUsedSize(mapLocalGlobalDofs.size());
      admin.setUsedCount(mapLocalGlobalDofs.size());
      admin.setFirstHole(mapLocalGlobalDofs.size());
254
255
256
    }
  }

257

258
259
260
261
262
263
264
265
266
267
  void ParallelDomainBase::testForMacroMesh()
  {
    FUNCNAME("ParallelDomainBase::testForMacroMesh()");

    int nMacroElements = 0;

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
    while (elInfo) {
      TEST_EXIT(elInfo->getLevel() == 0)
268
	("Mesh is already refined! This does not work with parallelization!\n");
269
270
271
272
273
274
275
276
277
278
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

279

Thomas Witkowski's avatar
Thomas Witkowski committed
280
  void ParallelDomainBase::synchVector(DOFVector<double> &vec)
281
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
282
    StdMpi<std::vector<double> > stdMpi(mpiComm);
283
284

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
285
	 sendIt != sendDofs.end(); ++sendIt) {
286
      std::vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
287
288
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
289
      
Thomas Witkowski's avatar
Thomas Witkowski committed
290
291
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
292
293
294
295

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

Thomas Witkowski's avatar
Thomas Witkowski committed
296
297
298
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
299

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

Thomas Witkowski's avatar
Thomas Witkowski committed
302
303
304
305
306
    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];
  }
307
308


Thomas Witkowski's avatar
Thomas Witkowski committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
  void ParallelDomainBase::synchVector(SystemVector &vec)
  {
    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])]);
323
324
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
325
      stdMpi.send(sendIt->first, dofs);
326
327
328
    }

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

Thomas Witkowski's avatar
Thomas Witkowski committed
332
    stdMpi.startCommunication<double>(MPI_DOUBLE);
333
334

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
335
336
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
337
338

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
339
340
341
342
343
      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++];
344
345
346
347
      }
    }
  }

348

Thomas Witkowski's avatar
Thomas Witkowski committed
349
350
351
352
353
354
355
356
357
358
359
360
  void ParallelDomainBase::removeBoundaryCondition(BoundaryIndexMap& boundaryMap)
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


361
362
  void ParallelDomainBase::checkMeshChange()
  {
363
364
    FUNCNAME("ParallelDomainBase::checkMeshChange()");

365
366
367
368
369
    // === 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);
370

371
    if (recvAllValues == 0)
372
373
      return;

374
375
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
376

377
378
379
380
381
    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.
382
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
383
384

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

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

392

393
      // === Check the boundaries and adapt mesh if necessary. ===
394

395
396
397
398
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

399
400
401
402
403
404
405
      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);
406
407
408
409

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

412
413

#if (DEBUG != 0)
414
    debug::writeMesh(feSpace, -1, "mesh");
415
416
417
418
419
420
#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. ===
421

422
423
424
425
426
427
428
429
430
431
432
433
434
    updateLocalGlobalNumbering();
  }

  
  bool ParallelDomainBase::checkAndAdaptBoundary(RankToBoundMap &allBound)
  {
    FUNCNAME("ParallelDomainBase::checkAndAdaptBoundary()");

    // === Create mesh structure codes for all ranks boundary elements. ===
       
    std::map<int, MeshCodeVec> sendCodes;
   
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
435
436
437
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
438
	elCode.init(boundIt->rankObj);
439
440
441
442
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
443
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
444
    stdMpi.send(sendCodes);
445
446
447
    stdMpi.recv(allBound);
    stdMpi.startCommunication<unsigned long int>(MPI_UNSIGNED_LONG);
 
448
    // === Compare received mesh structure codes. ===
449
    
450
451
    bool meshFitTogether = true;

452
453
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
      
454
455
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
456
      
457
458
      for (std::vector<AtomicBoundary>::iterator boundIt = it->second.begin();
	   boundIt != it->second.end(); ++boundIt) {
459

460
461
462
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
	
463
464
	if (elCode.getCode() != recvCodes[i].getCode()) {
	  TEST_EXIT_DBG(refineManager)("Refinement manager is not set correctly!\n");
465
466

	  bool b = fitElementToMeshCode(recvCodes[i], 
467
					boundIt->rankObj.el,
468
					boundIt->rankObj.subObj,
469
					boundIt->rankObj.ithObj, 
470
					boundIt->rankObj.elType);  
471

472
473
	  if (b)
	    meshFitTogether = false;
474
	}
475
	
476
	i++;
477
478
479
      }
    }

480
    return meshFitTogether;
481
  }
482
483
484
485


  bool ParallelDomainBase::fitElementToMeshCode(MeshStructure &code, 
						Element *el, 
486
487
						GeoIndex subObj,
						int ithObj, 
488
						int elType)
489
  {
490
    FUNCNAME("ParallelDomainBase::fitElementToMeshCode()");
491

492
493
    TEST_EXIT_DBG(el)("No element given!\n");

494
495
    if (code.empty())
      return false;
496
497
498

    int s1 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s2 = el->getSubObjOfChild(1, subObj, ithObj, elType);
499
500
501

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

502
503
504
    bool meshChanged = false;

    if (s1 != -1 && s2 != -1) {
505
506
507
508
509
510
511
      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);
      }

512
      meshChanged = fitElementToMeshCode2(code, stack, subObj, ithObj, elType);
513
514
      return meshChanged;
    }
515
516

    if (el->isLeaf()) {
517
518
519
      if (code.getNumElements() == 1 && code.isLeafElement())
	return false;     

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

532
      el->setMark(1);
533
534
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
535
      refineManager->refineFunction(elInfo);
536
    }
537
538

    if (s1 != -1) {
539
540
541
542
543
544
545
546
      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);
      }

547
548
      meshChanged |= 
	fitElementToMeshCode2(code, stack, subObj, s1, el->getChildType(elType));
549
    } else {
550
551
552
553
554
555
556
557
      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);
      }

558
559
      meshChanged |= 
	fitElementToMeshCode2(code, stack, subObj, s2, el->getChildType(elType));
560
561
562
    }

    return meshChanged;
563
564
  }

565

566
  bool ParallelDomainBase::fitElementToMeshCode2(MeshStructure &code, 
567
						 TraverseStack &stack,
568
569
						 GeoIndex subObj,
						 int ithObj, 
570
						 int elType)
571
  {
572
573
    FUNCNAME("ParallelDomainBase::fitElementToMeshCode2()");

574
575
    ElInfo *elInfo = stack.getElInfo();

576
    bool value = false;
577
578
579
580
581
582
583
584
585
586
587
    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);
588
     
589
590
      return value;
    }
591

592
593
    if (!elInfo)
      return value;
594

595
    if (el->isLeaf()) {
596
      el->setMark(1);
597
598
      refineManager->setMesh(el->getMesh());
      refineManager->setStack(&stack);
599
      refineManager->refineFunction(elInfo);
600
601
602
      value = true;
    }

603
604
    int s1 = el->getSubObjOfChild(0, subObj, ithObj, elType);
    int s2 = el->getSubObjOfChild(1, subObj, ithObj, elType);
605

606
    if (s1 != -1) {
607
      stack.traverseNext(elInfo);
608
      code.nextElement();
609
      value |= fitElementToMeshCode2(code, stack, subObj, s1, el->getChildType(elType));
610
611
612
613
614
      elInfo = stack.getElInfo();
    } else {
      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getElement() != el->getSecondChild());      
615
616
    }  

617
618
619
    TEST_EXIT_DBG(elInfo->getElement() == el->getSecondChild())
      ("This should not happen!\n");

620
    if (s2 != -1) {
621
      code.nextElement();
622
      value |= fitElementToMeshCode2(code, stack, subObj, s2, el->getChildType(elType));
623
624
    } else {
      int level = elInfo->getLevel();
625

626
627
628
629
      do {
	elInfo = stack.traverseNext(elInfo);
      } while (elInfo && elInfo->getLevel() > level);
    }
630

631
632
633
    return value;
  }

634
635
  
  void ParallelDomainBase::serialize(std::ostream &out, DofContainer &data)
Thomas Witkowski's avatar
Thomas Witkowski committed
636
  {    
637
    int vecSize = data.size();
638
    SerUtil::serialize(out, vecSize);
639
640
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = (*data[i]);
641
      SerUtil::serialize(out, dofIndex);
642
643
644
645
646
647
648
649
650
651
    }
  }


  void ParallelDomainBase::deserialize(std::istream &in, DofContainer &data,
				       std::map<int, const DegreeOfFreedom*> &dofMap)
  {
    FUNCNAME("ParallelDomainBase::deserialize()");

    int vecSize = 0;
652
    SerUtil::deserialize(in, vecSize);
653
654
655
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
656
      SerUtil::deserialize(in, dofIndex);
657
658
659
660
661
662
663
664
665
666
667
668

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

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


  void ParallelDomainBase::serialize(std::ostream &out, RankToDofContainer &data)
  {
    int mapSize = data.size();
669
    SerUtil::serialize(out, mapSize);
670
671
    for (RankToDofContainer::iterator it = data.begin(); it != data.end(); ++it) {
      int rank = it->first;
672
      SerUtil::serialize(out, rank);
673
674
675
676
677
678
679
680
681
      serialize(out, it->second);
    }
  }

  
  void ParallelDomainBase::deserialize(std::istream &in, RankToDofContainer &data,
				       std::map<int, const DegreeOfFreedom*> &dofMap)
  {
    int mapSize = 0;
682
    SerUtil::deserialize(in, mapSize);
683
684
    for (int i = 0; i < mapSize; i++) {
      int rank = 0;
685
      SerUtil::deserialize(in, rank);
686
687
688
689
      deserialize(in, data[rank], dofMap);      
    }
  }

690

691
  double ParallelDomainBase::setElemWeights(AdaptInfo *adaptInfo) 
692
  {
693
    FUNCNAME("ParallelDomainBase::setElemWeights()");
694

695
    double localWeightSum = 0.0;
696
    elemWeights.clear();
697
698
699
700
701
702
703
704
705
706
707
708
709
710
      
    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;
711

712
713
714
	elemWeights[elNum] = elWeight;
	localWeightSum += elWeight;
      }
715

716
      infile.close();
717
    } else {           
718
      TraverseStack stack;
719
      ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
720
      while (elInfo) {
721
722
723
	elemWeights[elInfo->getElement()->getIndex()] = 1.0;
	localWeightSum++;

724
	elInfo = stack.traverseNext(elInfo);
725
726
727
728
729
730
      }
    }

    return localWeightSum;
  }

731

732
  void ParallelDomainBase::partitionMesh(AdaptInfo *adaptInfo)
733
  {
734
735
    FUNCNAME("ParallelDomainBase::partitionMesh()");

736
737
738
739
740
741
742
743
744
745
746
747
    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);
  }

748

Thomas Witkowski's avatar
Thomas Witkowski committed
749
750
751
752
753
754
755
756
757
  void ParallelDomainBase::solveInitialProblem(AdaptInfo *adaptInfo)
  {     
    if (timeIF)
      timeIF->solveInitialProblem(adaptInfo);
    
    synchVector(*(probStat->getSolution()));
  }


758
  void ParallelDomainBase::createInteriorBoundaryInfo()
759
  {
760
    FUNCNAME("ParallelDomainBase::createInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
761

Thomas Witkowski's avatar
Thomas Witkowski committed
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
    // === 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);
781

Thomas Witkowski's avatar
Thomas Witkowski committed
782
783
784
785
786
787
788
789
    // === 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 ===
790
      // === indices. Now, we have to sort the corresponding list in this rank to   ===
Thomas Witkowski's avatar
Thomas Witkowski committed
791
      // === get the same order.                                                    ===
792
     
Thomas Witkowski's avatar
Thomas Witkowski committed
793
      for (int j = 0; j < static_cast<int>(rankIt->second.size()); j++) {
794

Thomas Witkowski's avatar
Thomas Witkowski committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
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
	// 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
  }


  void ParallelDomainBase::createMacroElementInteriorBoundaryInfo()
  {
    FUNCNAME("ParallelDomainBase::createMacroElementInteriorBoundaryInfo()");

874
875
    int nNeighbours = mesh->getGeo(NEIGH);
    int dim = mesh->getDim();
876
    GeoIndex subObj = INDEX_OF_DIM(dim - 1, dim);
877
878
879

    // === 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
880

881
    TraverseStack stack;
882
883
884
    ElInfo *elInfo = 
      stack.traverseFirst(mesh, -1, 
			  Mesh::CALL_LEAF_EL | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);
885
886
887
    while (elInfo) {
      Element *element = elInfo->getElement();
      PartitionElementData *partitionData = 
888
	dynamic_cast<PartitionElementData*>(element->getElementData(PARTITION_ED));
889

890
      // Check, if the element is within rank's partition.
891
      if (partitionData->getPartitionStatus() == IN) {
892
	for (int i = 0; i < nNeighbours; i++) {
893
894
895
896
	  if (!elInfo->getNeighbour(i))
	    continue;

	  PartitionElementData *neighbourPartitionData =
897
898
	    dynamic_cast<PartitionElementData*>(elInfo->getNeighbour(i)->
						getElementData(PARTITION_ED));
899

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

902
903
904
905
906
	    // 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. ===

907
	    AtomicBoundary bound;	    	    
908
909
	    bound.rankObj.el = element;
	    bound.rankObj.elIndex = element->getIndex();
910
	    bound.rankObj.elType = elInfo->getType();
911
	    bound.rankObj.subObj = subObj;
912
	    bound.rankObj.ithObj = i;
913
914

	    bound.neighObj.el = elInfo->getNeighbour(i);
915
	    bound.neighObj.elIndex = elInfo->getNeighbour(i)->getIndex();
916
	    bound.neighObj.elType = -1;
917
	    bound.neighObj.subObj = subObj;
918
	    bound.neighObj.ithObj = elInfo->getSideOfNeighbour(i);
919
	    
920
	    // Get rank number of the neighbouring element.
921
922
	    int otherElementRank = partitionVec[elInfo->getNeighbour(i)->getIndex()];

923
924
925
926
927
928
929
930
	    // === 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.                                         ===

931
	    if (BoundaryManager::isBoundaryPeriodic(elInfo->getBoundary(subObj, i))) {	      
932
933
934
935
936
	      // 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.
937
938
939
940
941
942
943
944
945
	      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);
	      }	      
946
	    }
947
948
949
950
951
952
 	  }
	}
      }

      elInfo = stack.traverseNext(elInfo);
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
953
  }
Thomas Witkowski's avatar
Thomas Witkowski committed
954
955


Thomas Witkowski's avatar
Thomas Witkowski committed
956
957
958
  void ParallelDomainBase::createSubstructureInteriorBoundaryInfo()
  {
    FUNCNAME("ParallelDomainBase::createSubstructureInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
959

960
961
962
    // === 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
963
964

    int dim = mesh->getDim();
965
    const BasisFunction *basFcts = feSpace->getBasisFcts();
966
    std::vector<DegreeOfFreedom> localIndices(basFcts->getNumber());
Thomas Witkowski's avatar
Thomas Witkowski committed
967
968
969

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

973
974
    // Maps each edge in the whole domain to the rank that ownes this edge.
    std::map<GlobalEdge, int> edgeOwner;
975
    // Maps each edge in ranks partition to the element object that contains this edge.
976
    std::map<GlobalEdge, BoundaryObject> rankEdges;
977
978
    // Stores to every element index a pointer to this element.
    std::map<int, Element*> elIndexMap;
979

980

Thomas Witkowski's avatar
Thomas Witkowski committed
981
    // === Traverse whole mesh and fill the maps defined above.                    ===
982

Thomas Witkowski's avatar
Thomas Witkowski committed
983
984
    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
985
986
    while (elInfo) {
      Element *el = elInfo->getElement();
987
988
989

      elIndexMap[el->getIndex()] = el;

990
991
992
993
      basFcts->getLocalIndices(el, feSpace->getAdmin(), localIndices);

      PartitionElementData *partitionData = dynamic_cast<PartitionElementData*>
	(el->getElementData(PARTITION_ED));
994
995
          
      // In 2d and 3d, traverse all vertices of current element.
996
      for (int i = 0; i < mesh->getGeo(VERTEX); i++) {
997
998
999
1000
	DegreeOfFreedom dof0 = localIndices[i];
	// Update the owner of the current vertex DOF.
	dofOwner[dof0] = max(dofOwner[dof0], partitionVec[el->getIndex()]);