MeshDistributor.cc 67 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
20
#include <boost/filesystem.hpp>

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

51
52
namespace AMDiS {

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

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

62

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

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

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

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

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

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

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

Thomas Witkowski's avatar
Thomas Witkowski committed
106
107
    if (partStr == "zoltan") {
#ifdef HAVE_ZOLTAN
108
      partitioner = new ZoltanPartitioner(&mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
109
110
111
112
#else
      ERROR_EXIT("AMDiS was compiled without Zoltan support. There you cannot make use of it!\n");
#endif
    }
113

Thomas Witkowski's avatar
Thomas Witkowski committed
114
115
116
    if (partStr == "simple")
      partitioner = new SimplePartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
117
118
119
120
    tmp = 0;
    GET_PARAMETER(0, name + "->box partitioning", "%d", &tmp);
    partitioner->setBoxPartitioning(static_cast<bool>(tmp));

121
    TEST_EXIT(partitioner)("Could not create partitioner \"%s\"!\n", partStr.c_str());
122
123
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
124

125
  void MeshDistributor::initParallelization()
126
  {
127
    FUNCNAME("MeshDistributor::initParallelization()");
128
129
130
131

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

132
133
    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");
134

Thomas Witkowski's avatar
Thomas Witkowski committed
135
#ifdef HAVE_ZOLTAN
136
137
138
    int a = 0;
    char *b = NULL;
    float zoltanVersion = 0.0;
139
    Zoltan_Initialize(a, &b, &zoltanVersion);
Thomas Witkowski's avatar
Thomas Witkowski committed
140
#endif
141

142
143
    elObjects.setFeSpace(feSpace);

144
145
146
    // 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).
147
    if (deserialized) {
148
149
      updateMacroElementInfo();

150
      setRankDofs();
151

152
      removePeriodicBoundaryConditions();
153

154
155
      macroElIndexMap.clear();
      macroElIndexTypeMap.clear();
156

157
      for (vector<MacroElement*>::iterator it = allMacroElements.begin();
158
	   it != allMacroElements.end(); ++it) {
159
160
161
162
	macroElIndexMap[(*it)->getIndex()] = (*it)->getElement();
	macroElIndexTypeMap[(*it)->getIndex()] = (*it)->getElType();
      }

163
      return;
164
    }
165

166

167
168
169
170
171
    // 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();

172
173
174
175
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

176
    // create an initial partitioning of the mesh
177
    partitioner->createInitialPartitioning();
178

179
    // set the element weights, which are 1 at the very first begin
180
    setInitialElementWeights();
181
182

    // and now partition the mesh    
183
184
    bool partitioningSucceed = partitioner->partition(elemWeights, INITIAL);
    TEST_EXIT(partitioningSucceed)("Initial partitioning does not work!\n");
185
    partitioner->createPartitionMap(partitionMap);
186

187

188
#if (DEBUG != 0)    
189
190
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
191
192
193
    if (mpiRank == 0) {
      int writePartMesh = 1;
      GET_PARAMETER(0, "dbg->write part mesh", "%d", &writePartMesh);
194

195
      if (writePartMesh > 0) {
196
	debug::writeElementIndexMesh(mesh, debugOutputDir + "elementIndex.vtu");
197
	ParallelDebug::writePartitioning(*this, debugOutputDir + "part.vtu");
198
      }
199
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
200
#endif
201

202

203
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
204

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

207
#if (DEBUG != 0)
208
    ParallelDebug::printBoundaryInfo(*this);
209
210
#endif

211
212
213
214
215
    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))) {
216
217
218

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

219
220
221
222
223
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
224
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
225
226
227
228
229
230
231
232
233
	}
      }
    }

    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))) {
234
235
236

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

237
238
239
240
241
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
242
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
243
244
245
	}
      }
    }
246

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
247
248
249
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
250

251
252
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
253

254
255
256
    // 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.
257
    for (map<BoundaryType, VertexVector*>::iterator it = mesh->getPeriodicAssociations().begin();
258
259
	 it != mesh->getPeriodicAssociations().end(); ++it)
      const_cast<DOFAdmin&>(mesh->getDofAdmin(0)).removeDOFContainer(dynamic_cast<DOFContainer*>(it->second));
260

261
    updateLocalGlobalNumbering();
262

263
264
265
266
267
268
    // === 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();

269
270
    // === If in debug mode, make some tests. ===

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

274
    ParallelDebug::testAllElements(*this);
275
    debug::testSortedDofs(mesh, elMap);
276
    ParallelDebug::testInteriorBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
277

278
    debug::writeMesh(feSpace, -1, debugOutputDir + "macro_mesh");   
279
280

    MSG("Debug mode tests finished!\n");
281
#endif
282

283
    // === Create periodic DOF mapping, if there are periodic boundaries. ===
284

285
    createPeriodicMap();
286

287
288
289
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
290

291
    // === Global refinements. ===
292
    
Thomas Witkowski's avatar
Thomas Witkowski committed
293
    int globalRefinement = 0;
294
    GET_PARAMETER(0, mesh->getName() + "->global refinements", "%d", &globalRefinement);
295
    
Thomas Witkowski's avatar
Thomas Witkowski committed
296
    if (globalRefinement > 0) {
297
      refineManager->globalRefine(mesh, globalRefinement);
298

299
      updateLocalGlobalNumbering();
300
301

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

304
      createPeriodicMap();
305
306
307
308

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

311

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

314
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
315

316

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

319
    removePeriodicBoundaryConditions();
320
321
  }

322

323
324
325
326
327
  void MeshDistributor::addProblemStat(ProblemVec *probVec)
  {
    FUNCNAME("MeshDistributor::addProblemVec()");

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

354
      partitioner->setMesh(mesh);
355
356
357
358
    }

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

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

    int readSerialization = 0;
377
378
    GET_PARAMETER(0, probVec->getName() + "->input->read serialization", "%d", 
		  &readSerialization);
379
    if (readSerialization) {
380
      string filename = "";
381
      GET_PARAMETER(0, probVec->getName() + "->input->serialization filename", &filename);
382
      filename += ".p" + lexical_cast<string>(mpiRank);
383
      MSG("Start deserialization with %s\n", filename.c_str());
384
      ifstream in(filename.c_str());
385
386
387
388

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

389
      probVec->deserialize(in);
390
      in.close();
391
392
      MSG("Deserialization from file: %s\n", filename.c_str());

393
394
395
396
397
398
      filename = "";
      GET_PARAMETER(0, name + "->input->serialization filename", &filename);
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel deserialization file!\n");
      
399
      string rankFilename = filename + ".p" + lexical_cast<string>(mpiRank);
400
401
402
403
404
405
406
407
408
      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;
409
410
411
412
413
414
    }

    probStat.push_back(probVec);
  }


415
  void MeshDistributor::exitParallelization()
416
  {}
417

418
  
419
  void MeshDistributor::testForMacroMesh()
420
  {
421
    FUNCNAME("MeshDistributor::testForMacroMesh()");
422
423
424
425
426
427
428

    int nMacroElements = 0;

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

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
433
434
435
436
437
438
439
440
441
442
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

443

444
  void MeshDistributor::synchVector(DOFVector<double> &vec)
445
  {
446
    StdMpi<vector<double> > stdMpi(mpiComm);
447
448

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
449
	 sendIt != sendDofs.end(); ++sendIt) {
450
      vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
451
452
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
453
      
Thomas Witkowski's avatar
Thomas Witkowski committed
454
455
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
456
457
458
459

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

Thomas Witkowski's avatar
Thomas Witkowski committed
460
461
462
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
463

464
    stdMpi.startCommunication();
465

Thomas Witkowski's avatar
Thomas Witkowski committed
466
467
468
469
470
    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];
  }
471
472


473
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
474
  {
475
    int nComponents = vec.getSize();
476
    StdMpi<vector<double> > stdMpi(mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
477
478
479

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
	 sendIt != sendDofs.end(); ++sendIt) {
480
      vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
481
482
483
484
485
486
487
      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])]);
488
489
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
490
      stdMpi.send(sendIt->first, dofs);
491
492
493
    }

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

497
    stdMpi.startCommunication();
498
499

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
500
501
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
502
503

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
504
505
506
507
508
      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++];
509
510
511
512
      }
    }
  }

513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
  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);
    }

537
538

    FixRefinementPatch::connectedEdges.clear();
539
540
541
542
543
544
545
546

    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;
547
548
549
550
      std::map<int, int> edgeNoInEl;

      for (unsigned int i = 0; i < edgeEls.size(); i++) {
	if (rankMacroEls.count(edgeEls[i].elIndex)) {
551
552
553
554
	  if (el0.empty())
	    el0.insert(edgeEls[i].elIndex);
	  else
	    el1.insert(edgeEls[i].elIndex);
555
556
557
558

	  edgeNoInEl[edgeEls[i].elIndex] = edgeEls[i].ithObject;
	}
      }
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
            
      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()) {
584
585
	MSG("Unvalid 3D mesh with %d (%d - %d) elements on this edge!\n", 
	    edgeEls.size(), el0.size(), el1.size());
586

587
588
589
590
591
592
593
	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");
594

595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
	    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));
	  }
	}
      }
    }
620
621
622
  }


623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
  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);
      }
    }
  }


642
643
  void MeshDistributor::removePeriodicBoundaryConditions()
  {
644
645
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

646
647
648
649
650
651
652
653
    // 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())
654
	    removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
	}
	
	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);
    }    
672
673
674

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
675
676
677
678
  }


  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
679
680
681
682
683
684
685
686
687
688
689
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


690
  void MeshDistributor::checkMeshChange(bool tryRepartition)
691
  {
692
    FUNCNAME("MeshDistributor::checkMeshChange()");
693

694
695
    double first = MPI::Wtime();

696
697
698
699
700
    // === 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);
701

702
    if (recvAllValues == 0)
703
704
      return;

705
706
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
707
   
708
    do {
709
710
      bool meshChanged = false;

711
712
      // To check the interior boundaries, the ownership of the boundaries is not 
      // important. Therefore, we add all boundaries to one boundary container.
713
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
714
715

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

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

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

742

743
      // === Check the boundaries and adapt mesh if necessary. ===
744
745
746
747
#if (DEBUG != 0)
      MSG("Run checkAndAdaptBoundary ...\n");
#endif

748
      meshChanged |= checkAndAdaptBoundary(allBound);
749
750
751

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

752
      int sendValue = static_cast<int>(meshChanged);
753
754
      recvAllValues = 0;
      mpiComm.Allreduce(&sendValue, &recvAllValues, 1, MPI_INT, MPI_SUM);
755
756

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

759
#if (DEBUG != 0)
760
    debug::writeMesh(feSpace, -1, debugOutputDir + "mesh");
761
762
#endif

763

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

766
767
    updateLocalGlobalNumbering();

768

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

Thomas Witkowski's avatar
Thomas Witkowski committed
771
    createPeriodicMap();
772

773
774
775
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
776
777


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

780
    nMeshChangesAfterLastRepartitioning++;
781

782
783
784
785

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

786
787
    if (tryRepartition &&
	repartitioningAllowed && 
788
789
790
	nMeshChangesAfterLastRepartitioning >= repartitionIthChange) {
      repartitionMesh();
      nMeshChangesAfterLastRepartitioning = 0;
791
    }
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810

    // === 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);
    }
811
812
813
  }

  
814
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
815
  {
816
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
817
818
819

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

824
      for (vector<AtomicBoundary>::iterator boundIt = it->second.begin();
825
826
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
827
	elCode.init(boundIt->rankObj);
828
829
830
831
	sendCodes[it->first].push_back(elCode);
      }
    }

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

842
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
843
     
844
845
      MeshCodeVec &recvCodes = stdMpi.getRecvData()[it->first];
      int i = 0;
846
      
847
      for (vector<AtomicBoundary>::iterator boundIt = it->second.begin();
848
	   boundIt != it->second.end(); ++boundIt, i++) {
849

850
851
	MeshStructure elCode;	
	elCode.init(boundIt->rankObj);
852

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

856
857
	  MeshManipulation mm(feSpace);
	  meshChanged |= mm.fitElementToMeshCode(recvCodes[i], boundIt->rankObj);
858
 	}
859
860
861
      }
    }

862
    return meshChanged;
863
  }
864
865


866
  void MeshDistributor::serialize(ostream &out, DofContainer &data)
Thomas Witkowski's avatar
Thomas Witkowski committed
867
  {    
868
    int vecSize = data.size();
869
    SerUtil::serialize(out, vecSize);
870
    for (int i = 0; i < vecSize; i++) {
871
      int dofIndex = *(data[i]);
872
      SerUtil::serialize(out, dofIndex);
873
874
875
876
    }
  }


877
878
  void MeshDistributor::deserialize(istream &in, DofContainer &data,
				    map<int, const DegreeOfFreedom*> &dofMap)
879
  {
880
    FUNCNAME("MeshDistributor::deserialize()");
881
882

    int vecSize = 0;
883
    SerUtil::deserialize(in, vecSize);
884
    data.clear();
885
886
887
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
888
      SerUtil::deserialize(in, dofIndex);
889
890
891
892
893
894
895
896
897

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

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