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


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

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

52
53
namespace AMDiS {

Thomas Witkowski's avatar
Thomas Witkowski committed
54
  using boost::lexical_cast;
55
  using namespace boost::filesystem;
56
  using namespace std;
Thomas Witkowski's avatar
Thomas Witkowski committed
57

58
59
60
61
62
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

63

64
  MeshDistributor::MeshDistributor(string str)
65
66
67
68
69
70
71
    : probStat(0),
      name(str),
      feSpace(NULL),
      mesh(NULL),
      refineManager(NULL),
      info(10),
      partitioner(NULL),
72
      nRankDofs(0),
73
      nOverallDofs(0),
74
      rstart(0),
75
      deserialized(false),
76
      writeSerializationFile(false),
77
      repartitioningAllowed(false),
78
      repartitionIthChange(20),
79
80
      nMeshChangesAfterLastRepartitioning(0),
      repartitioningCounter(0),
81
      debugOutputDir(""),
82
      lastMeshChangeIndex(0)
83
  {
84
    FUNCNAME("MeshDistributor::ParalleDomainBase()");
Thomas Witkowski's avatar
Thomas Witkowski committed
85

86
87
88
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
89
90
91
92

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

94
95
    GET_PARAMETER(0, name + "->debug output dir", &debugOutputDir);
    GET_PARAMETER(0, name + "->repartition ith change", "%d", &repartitionIthChange);
96
97
98
99

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

101
102
103
104
105
106
107
108
109
    string partStr = "parmetis";
    GET_PARAMETER(0, name + "->partitioner", &partStr);

    if (partStr == "parmetis") 
      partitioner = new ParMetisPartitioner(&mpiComm);

    if (partStr == "zoltan")
      partitioner = new ZoltanPartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
110
111
112
    if (partStr == "simple")
      partitioner = new SimplePartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
113
114
115
116
    tmp = 0;
    GET_PARAMETER(0, name + "->box partitioning", "%d", &tmp);
    partitioner->setBoxPartitioning(static_cast<bool>(tmp));

117
    TEST_EXIT(partitioner)("Could not create partitioner \"%s\"!\n", partStr.c_str());
118
119
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
120

121
  void MeshDistributor::initParallelization()
122
  {
123
    FUNCNAME("MeshDistributor::initParallelization()");
124
125
126
127

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

128
129
    TEST_EXIT(feSpace)("No FE space has been defined for the mesh distributor!\n");
    TEST_EXIT(mesh)("No mesh has been defined for the mesh distributor!\n");
130

131
132
133
    int a = 0;
    char *b = NULL;
    float zoltanVersion = 0.0;
134
135
    Zoltan_Initialize(a, &b, &zoltanVersion);

136
137
    elObjects.setFeSpace(feSpace);

138
139
140
    // If the problem has been already read from a file, we need only to set
    // isRankDofs to all matrices and rhs vector and to remove periodic 
    // boundary conditions (if there are some).
141
    if (deserialized) {
142
143
      updateMacroElementInfo();

144
      setRankDofs();
145

146
      removePeriodicBoundaryConditions();
147

148
149
      macroElIndexMap.clear();
      macroElIndexTypeMap.clear();
150

151
      for (vector<MacroElement*>::iterator it = allMacroElements.begin();
152
	   it != allMacroElements.end(); ++it) {
153
154
155
156
	macroElIndexMap[(*it)->getIndex()] = (*it)->getElement();
	macroElIndexTypeMap[(*it)->getIndex()] = (*it)->getElType();
      }

157
      return;
158
    }
159

160

161
162
163
164
165
    // 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();

166
167
168
169
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

170
    // create an initial partitioning of the mesh
171
    partitioner->createInitialPartitioning();
172

173
    // set the element weights, which are 1 at the very first begin
174
    setInitialElementWeights();
175
176

    // and now partition the mesh    
177
178
    bool partitioningSucceed = partitioner->partition(elemWeights, INITIAL);
    TEST_EXIT(partitioningSucceed)("Initial partitioning does not work!\n");
179
    partitioner->createPartitionMap(partitionMap);
180

181

182
#if (DEBUG != 0)    
183
184
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
185
186
187
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
188

189
      if (writePartMesh > 0) {
190
	debug::writeElementIndexMesh(mesh, debugOutputDir + "elementIndex.vtu");
191
	ParallelDebug::writePartitioning(*this, debugOutputDir + "part.vtu");
192
      }
193
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
194
#endif
195

196

197
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
198

199
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
200

201
#if (DEBUG != 0)
202
    ParallelDebug::printBoundaryInfo(*this);
203
204
#endif

205
206
207
208
209
    for (deque<MacroElement*>::iterator it = mesh->firstMacroElement();
	 it != mesh->endOfMacroElements(); ++it) {
      for (int i = 0; i < mesh->getGeo(NEIGH); i++) {
	if ((*it)->getNeighbour(i) && 
	    mesh->isPeriodicAssociation((*it)->getBoundary(i))) {
210
211
212

	  int neighIndex = (*it)->getNeighbour(i)->getIndex();

213
214
215
216
217
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
218
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
219
220
221
222
223
224
225
226
227
	}
      }
    }

    for (vector<MacroElement*>::iterator it = allMacroElements.begin();
	 it != allMacroElements.end(); ++it) {
      for (int i = 0; i < mesh->getGeo(NEIGH); i++) {
	if ((*it)->getNeighbour(i) && 
	    mesh->isPeriodicAssociation((*it)->getBoundary(i))) {
228
229
230

	  int neighIndex = (*it)->getNeighbour(i)->getIndex();

231
232
233
234
235
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
236
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
237
238
239
	}
      }
    }
240

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
241
242
243
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
244

245
246
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
247

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

255
    updateLocalGlobalNumbering();
256

257
258
259
260
261
262
    // === In 3D we have to make some test, if the resulting mesh is valid. If   ===
    // === it is not valid, there is no possiblity yet to fix this problem, just ===
    // === exit with an error message.                                           ===
    
    check3dValidMesh();

263
264
    // === If in debug mode, make some tests. ===

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

268
    ParallelDebug::testAllElements(*this);
269
    debug::testSortedDofs(mesh, elMap);
270
    ParallelDebug::testInteriorBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
271

272
    debug::writeMesh(feSpace, -1, debugOutputDir + "macro_mesh");   
273
274

    MSG("Debug mode tests finished!\n");
275
#endif
276

277
    // === Create periodic DOF mapping, if there are periodic boundaries. ===
278

279
    createPeriodicMap();
280

281
282
283
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
284

285
    // === Global refinements. ===
286
    
Thomas Witkowski's avatar
Thomas Witkowski committed
287
    int globalRefinement = 0;
288
    GET_PARAMETER(0, mesh->getName() + "->global refinements", "%d", &globalRefinement);
289
    
Thomas Witkowski's avatar
Thomas Witkowski committed
290
    if (globalRefinement > 0) {
291
      refineManager->globalRefine(mesh, globalRefinement);
292

293
      updateLocalGlobalNumbering();
294
295

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

298
      createPeriodicMap();
299
300
301
302

#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
Thomas Witkowski's avatar
Thomas Witkowski committed
303
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
304

305

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

308
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
309

310

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

313
    removePeriodicBoundaryConditions();
314
315
  }

316

317
318
319
320
321
  void MeshDistributor::addProblemStat(ProblemVec *probVec)
  {
    FUNCNAME("MeshDistributor::addProblemVec()");

    if (feSpace != NULL) {
322
      vector<FiniteElemSpace*> feSpaces = probVec->getFeSpaces();
323
324
325
326
327
328
329
330
331
332
333
      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");
334
      TEST_EXIT(mesh->getDofAdmin(0).getNumberOfPreDofs(VERTEX) == 0)
335
336
337
338
339
340
341
342
343
344
345
346
347
	("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());
      }

348
      partitioner->setMesh(mesh);
349
350
351
352
    }

    // Create parallel serialization file writer, if needed.
    int writeSerialization = 0;
353
354
355
    GET_PARAMETER(0, probVec->getName() + "->output->write serialization", "%d", 
		  &writeSerialization);
    if (writeSerialization && !writeSerializationFile) {
356
      string filename = "";
357
358
359
360
      GET_PARAMETER(0, name + "->output->serialization filename", &filename);
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel serialization file!\n");
361
362
363
364
365

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

    int readSerialization = 0;
371
372
    GET_PARAMETER(0, probVec->getName() + "->input->read serialization", "%d", 
		  &readSerialization);
373
    if (readSerialization) {
374
      string filename = "";
375
      GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
376
      filename += ".p" + lexical_cast<string>(mpiRank);
377
      MSG("Start deserialization with %s\n", filename.c_str());
378
      ifstream in(filename.c_str());
379
380
381
382

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

383
      probVec->deserialize(in);
384
      in.close();
385
386
      MSG("Deserialization from file: %s\n", filename.c_str());

387
388
389
390
391
392
      filename = "";
      GET_PARAMETER(0, name + "->input->serialization filename", &filename);
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel deserialization file!\n");
      
393
      string rankFilename = filename + ".p" + lexical_cast<string>(mpiRank);
394
395
396
397
398
399
400
401
402
      in.open(rankFilename.c_str());
      
      TEST_EXIT(!in.fail())("Could not open parallel deserialization file: %s\n",
			    filename.c_str());
      
      deserialize(in);
      in.close();
      MSG("Deserializtion of mesh distributor from file: %s\n", rankFilename.c_str());
      deserialized = true;
403
404
405
406
407
408
    }

    probStat.push_back(probVec);
  }


409
  void MeshDistributor::exitParallelization()
410
  {}
411

412
  
413
  void MeshDistributor::testForMacroMesh()
414
  {
415
    FUNCNAME("MeshDistributor::testForMacroMesh()");
416
417
418
419
420
421
422

    int nMacroElements = 0;

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

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
427
428
429
430
431
432
433
434
435
436
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

437

438
  void MeshDistributor::synchVector(DOFVector<double> &vec)
439
  {
440
    StdMpi<vector<double> > stdMpi(mpiComm);
441
442

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
443
	 sendIt != sendDofs.end(); ++sendIt) {
444
      vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
445
446
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
447
      
Thomas Witkowski's avatar
Thomas Witkowski committed
448
449
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
450
451
452
453

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

Thomas Witkowski's avatar
Thomas Witkowski committed
454
455
456
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
457

458
    stdMpi.startCommunication();
459

Thomas Witkowski's avatar
Thomas Witkowski committed
460
461
462
463
464
    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];
  }
465
466


467
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
468
  {
469
    int nComponents = vec.getSize();
470
    StdMpi<vector<double> > stdMpi(mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
471
472
473

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
	 sendIt != sendDofs.end(); ++sendIt) {
474
      vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
475
476
477
478
479
480
481
      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])]);
482
483
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
484
      stdMpi.send(sendIt->first, dofs);
485
486
487
    }

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

491
    stdMpi.startCommunication();
492
493

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
494
495
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
496
497

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
498
499
500
501
502
      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++];
503
504
505
506
      }
    }
  }

507

508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
  void MeshDistributor::check3dValidMesh()
  {
    FUNCNAME("MeshDistributor::check3dValidMesh()");

    if (mesh->getDim() != 3)
      return;

    std::set<DofEdge> allEdges;
    std::set<int> rankMacroEls;

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, 0, Mesh::CALL_EL_LEVEL);
    while (elInfo) {
      for (int i = 0; i < 4; i++) {
	ElementObjectData elData(elInfo->getElement()->getIndex(), i);
	allEdges.insert(elObjects.getEdgeLocalMap(elData));
      }

      rankMacroEls.insert(elInfo->getElement()->getIndex());

      elInfo = stack.traverseNext(elInfo);
    }

531
532

    FixRefinementPatch::connectedEdges.clear();
533
534
535
536
537
538
539
540

    for (std::set<DofEdge>::iterator it = allEdges.begin(); it != allEdges.end(); ++it) {
      vector<ElementObjectData>& edgeEls = elObjects.getElements(*it);

      TEST_EXIT_DBG(edgeEls.size() > 0)
	("No edge %d/%d in elObjDB!\n", it->first, it->second);

      std::set<int> el0, el1;
541
542
543
544
      std::map<int, int> edgeNoInEl;

      for (unsigned int i = 0; i < edgeEls.size(); i++) {
	if (rankMacroEls.count(edgeEls[i].elIndex)) {
545
546
547
548
	  if (el0.empty())
	    el0.insert(edgeEls[i].elIndex);
	  else
	    el1.insert(edgeEls[i].elIndex);
549
550
551
552

	  edgeNoInEl[edgeEls[i].elIndex] = edgeEls[i].ithObject;
	}
      }
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
            
      TEST_EXIT_DBG(!el0.empty())("Should not happen!\n");

      if (el1.empty())
	continue;
      
      bool found = false;      
      do {
	found = false;
	for (std::set<int>::iterator elIt = el0.begin(); elIt != el0.end(); ++elIt) {
	  for (int i = 0; i < 4; i++) {
	    int neighEl = macroElementNeighbours[*elIt][i];
	    if (neighEl != -1 && el1.count(neighEl)) {
	      el0.insert(neighEl);
	      el1.erase(neighEl);
	      found = true;
	    }
	  }
	  
	  if (found)
	    break;
	}
      } while (found);
      
      if (!el1.empty()) {
578
579
	MSG("Unvalid 3D mesh with %d (%d - %d) elements on this edge!\n", 
	    edgeEls.size(), el0.size(), el1.size());
580

581
582
583
584
585
586
587
	for (std::set<int>::iterator elIt0 = el0.begin(); elIt0 != el0.end(); ++elIt0) {
	  for (std::set<int>::iterator elIt1 = el1.begin(); elIt1 != el1.end(); ++elIt1) {

	    TEST_EXIT_DBG(macroElIndexMap.count(*elIt0))("Should not happen!\n");
	    TEST_EXIT_DBG(macroElIndexMap.count(*elIt1))("Should not happen!\n");
	    TEST_EXIT_DBG(edgeNoInEl.count(*elIt0))("Should not happen!\n");
	    TEST_EXIT_DBG(edgeNoInEl.count(*elIt1))("Should not happen!\n");
588

589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
	    pair<Element*, int> edge0 = 
	      make_pair(macroElIndexMap[*elIt0], edgeNoInEl[*elIt0]);
	    pair<Element*, int> edge1 = 
	      make_pair(macroElIndexMap[*elIt1], edgeNoInEl[*elIt1]);

	    DofEdge dofEdge0 = edge0.first->getEdge(edge0.second);
	    DofEdge dofEdge1 = edge1.first->getEdge(edge1.second);

	    WorldVector<double> c0, c1;
	    mesh->getDofIndexCoords(dofEdge0.first, feSpace, c0);
	    mesh->getDofIndexCoords(dofEdge0.second, feSpace, c1);

	    MSG("FOUND EDGE: %d %d with coords %f %f %f   %f %f %f\n",
		dofEdge0.first, dofEdge0.second, 
		c0[0], c0[1], c0[2],
		c1[0], c1[1], c1[2]);

	    TEST_EXIT_DBG(dofEdge0 == dofEdge1)("Should noth happen!\n");

	    FixRefinementPatch::connectedEdges.push_back(make_pair(edge0, edge1));
	    FixRefinementPatch::connectedEdges.push_back(make_pair(edge1, edge0));
	  }
	}
      }
    }
614
615
616
  }


617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
  void MeshDistributor::setRankDofs()
  {
    for (unsigned int i = 0; i < probStat.size(); i++) {
      int nComponents = probStat[i]->getNumComponents();
      for (int j = 0; j < nComponents; j++) {
	for (int k = 0; k < nComponents; k++)
	  if (probStat[i]->getSystemMatrix(j, k))
	    probStat[i]->getSystemMatrix(j, k)->setRankDofs(isRankDof);

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


636
637
  void MeshDistributor::removePeriodicBoundaryConditions()
  {
638
639
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

640
641
642
643
644
645
646
647
    // Remove periodic boundaries in boundary manager on matrices and vectors.
    for (unsigned int i = 0; i < probStat.size(); i++) {
      int nComponents = probStat[i]->getNumComponents();

      for (int j = 0; j < nComponents; j++) {
	for (int k = 0; k < nComponents; k++) {
	  DOFMatrix* mat = probStat[i]->getSystemMatrix(j, k);
	  if (mat && mat->getBoundaryManager())
648
	    removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
	}
	
	if (probStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(probStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
	
	if (probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(probStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
      }
    }

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

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
669
670
671
672
  }


  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
673
674
675
676
677
678
679
680
681
682
683
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


684
  void MeshDistributor::checkMeshChange(bool tryRepartition)
685
  {
686
    FUNCNAME("MeshDistributor::checkMeshChange()");
687

688
689
    double first = MPI::Wtime();

690
691
692
693
694
    // === 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);
695

696
    if (recvAllValues == 0)
697
698
      return;

699
700
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
701
   
702
    do {
703
704
      bool meshChanged = false;

705
706
      // To check the interior boundaries, the ownership of the boundaries is not 
      // important. Therefore, we add all boundaries to one boundary container.
707
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
708
709

      for (InteriorBoundary::iterator it(myIntBoundary); !it.end(); ++it)
710
711
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
712
 	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
713
714

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

719
720
      for (InteriorBoundary::iterator it(periodicBoundary); !it.end(); ++it) {
	if (it.getRank() == mpiRank) {
721
722
723
724
725
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE)) {
	    MeshStructure elCode;
	    elCode.init(it->rankObj);
	    
726
	    MeshManipulation mm(feSpace);
727
	    meshChanged |= mm.fitElementToMeshCode(elCode, it->neighObj);
728
	  }
729
730
731
732
733
734
	} else {
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
	    allBound[it.getRank()].push_back(*it);	
	}
      }
735

736

737
      // === Check the boundaries and adapt mesh if necessary. ===
738
739
740
741
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

742
      meshChanged |= checkAndAdaptBoundary(allBound);
743
744
745

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

746
      int sendValue = static_cast<int>(meshChanged);
747
748
      recvAllValues = 0;
      mpiComm.Allreduce(&sendValue, &recvAllValues, 1, MPI_INT, MPI_SUM);
749
750

      MSG("Mesh changed on %d ranks!\n", recvAllValues);
751
    } while (recvAllValues != 0);
752

753
#if (DEBUG != 0)
754
    debug::writeMesh(feSpace, -1, debugOutputDir + "mesh");
755
756
#endif

757

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

760
761
    updateLocalGlobalNumbering();

762

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

Thomas Witkowski's avatar
Thomas Witkowski committed
765
    createPeriodicMap();
766

767
768
769
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
770
771


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

774
    nMeshChangesAfterLastRepartitioning++;
775

776
777
778
779

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

780
781
    if (tryRepartition &&
	repartitioningAllowed && 
782
783
784
	nMeshChangesAfterLastRepartitioning >= repartitionIthChange) {
      repartitionMesh();
      nMeshChangesAfterLastRepartitioning = 0;
785
    }
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804

    // === Print imbalance factor. ===

    vector<int> nDofsInRank(mpiSize);
    int nDofs = mesh->getDofAdmin(0).getUsedDofs();
    mpiComm.Gather(&nDofs, 1, MPI_INT, &(nDofsInRank[0]), 1, MPI_INT, 0);

    if (mpiRank == 0) {
      int nOverallDofs = 0;
      int maxDofs = numeric_limits<int>::min();
      for (int i = 0; i < mpiSize; i++) {
	nOverallDofs += nDofsInRank[i];
	maxDofs = std::max(maxDofs, nDofsInRank[i]);
      }      
      int avrgDofs = nOverallDofs / mpiSize;
      double imbalance = (static_cast<double>(maxDofs - avrgDofs) /  avrgDofs) * 100.0;

      MSG("Imbalancing factor: %.1f\%\n", imbalance);
    }
805
806
807
  }

  
808
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
809
  {
810
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
811
812
813

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

818
      for (vector<AtomicBoundary>::iterator boundIt = it->second.begin();
819
820
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
821
	elCode.init(boundIt->rankObj);
822
823
824
825
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
826
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
827
    stdMpi.send(sendCodes);
828
829
830
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it)
      stdMpi.recv(it->first);
    stdMpi.startCommunication();
831
 
832
    // === Compare received mesh structure codes. ===
833
    
834
    bool meshChanged = false;
835

836
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
837
     
838
839
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
840
      
841
      for (vector<AtomicBoundary>::iterator boundIt = it->second.begin();
842
	   boundIt != it->second.end(); ++boundIt, i++) {
843

844
845
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
846

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

850
851
	  MeshManipulation mm(feSpace);
	  meshChanged |= mm.fitElementToMeshCode(recvCodes[i], boundIt->rankObj);
852
 	}
853
854
855
      }
    }

856
    return meshChanged;
857
  }
858
859


860
  void MeshDistributor::serialize(ostream &out, DofContainer &data)
Thomas Witkowski's avatar
Thomas Witkowski committed
861
  {    
862
    int vecSize = data.size();
863
    SerUtil::serialize(out, vecSize);
864
    for (int i = 0; i < vecSize; i++) {
865
      int dofIndex = *(data[i]);
866
      SerUtil::serialize(out, dofIndex);
867
868
869
870
    }
  }


871
872
  void MeshDistributor::deserialize(istream &in, DofContainer &data,
				    map<int, const DegreeOfFreedom*> &dofMap)
873
  {
874
    FUNCNAME("MeshDistributor::deserialize()");
875
876

    int vecSize = 0;
877
    SerUtil::deserialize(in, vecSize);
878
    data.clear();
879
880
881
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
882
      SerUtil::deserialize(in, dofIndex);
883
884
885
886
887
888
889
890
891

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

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


892
  void MeshDistributor::serialize(ostream &out, RankToDofContainer &data)
893
894
  {
    int mapSize = data.size();
895
    SerUtil::serialize(out, mapSize);
896
897
    for (RankToDofContainer::iterator it = data.begin(); it != data.end(); ++it) {
      int rank = it->first;