MeshDistributor.cc 70 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/CheckerPartitioner.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"
47
#include "ProblemStat.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
48
#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
  MeshDistributor* MeshDistributor::globalMeshDistributor = NULL;

60
61
62
  const Flag MeshDistributor::BOUNDARY_SUBOBJ_SORTED              = 0X01L;
  const Flag MeshDistributor::BOUNDARY_FILL_INFO_SEND_DOFS        = 0X02L;
  const Flag MeshDistributor::BOUNDARY_FILL_INFO_RECV_DOFS        = 0X04L;
Thomas Witkowski's avatar
Thomas Witkowski committed
63

64
65
66
67
68
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

69

70
  MeshDistributor::MeshDistributor()
71
    : problemStat(0),
72
      initialized(false),
73
      name("parallel"),
74
75
76
77
78
      feSpace(NULL),
      mesh(NULL),
      refineManager(NULL),
      info(10),
      partitioner(NULL),
79
      nRankDofs(0),
80
      nOverallDofs(0),
81
      rstart(0),
82
      deserialized(false),
83
      writeSerializationFile(false),
84
      repartitioningAllowed(false),
85
      repartitionIthChange(20),
86
87
      nMeshChangesAfterLastRepartitioning(0),
      repartitioningCounter(0),
88
      debugOutputDir(""),
Thomas Witkowski's avatar
Thomas Witkowski committed
89
90
      lastMeshChangeIndex(0),
      createBoundaryDofFlag(0)
91
  {
92
    FUNCNAME("MeshDistributor::ParalleDomainBase()");
Thomas Witkowski's avatar
Thomas Witkowski committed
93

94
95
96
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
97
98

    int tmp = 0;
99
    Parameters::get(name + "->repartitioning", tmp);
100
    repartitioningAllowed = (tmp > 0);
101

102
103
    Parameters::get(name + "->debug output dir", debugOutputDir);
    Parameters::get(name + "->repartition ith change", repartitionIthChange);
104
105

    tmp = 0;
106
    Parameters::get(name + "->log main rank", tmp);
107
    Msg::outputMainRank = (tmp > 0);
108

109
    string partStr = "parmetis";
110
    Parameters::get(name + "->partitioner", partStr);
111
112
113
114

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

Thomas Witkowski's avatar
Thomas Witkowski committed
115
116
    if (partStr == "zoltan") {
#ifdef HAVE_ZOLTAN
117
      partitioner = new ZoltanPartitioner(&mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
118
#else
Thomas Witkowski's avatar
Thomas Witkowski committed
119
      ERROR_EXIT("AMDiS was compiled without Zoltan support. Therefore you cannot make use of it!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
120
121
#endif
    }
122

123
124
125
    if (partStr == "checker")
      partitioner = new CheckerPartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
126
127
128
    if (partStr == "simple")
      partitioner = new SimplePartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
129
    tmp = 0;
130
    Parameters::get(name + "->box partitioning", tmp);
Thomas Witkowski's avatar
Thomas Witkowski committed
131
132
    partitioner->setBoxPartitioning(static_cast<bool>(tmp));

133
    TEST_EXIT(partitioner)("Could not create partitioner \"%s\"!\n", partStr.c_str());
134
135
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
136

137
  void MeshDistributor::initParallelization()
138
  {
139
    FUNCNAME("MeshDistributor::initParallelization()");
140
141
142
143

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

144
145
    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");
146
    TEST_EXIT(!initialized)("MeshDistributor is already initialized!\n");
147

Thomas Witkowski's avatar
Thomas Witkowski committed
148
#ifdef HAVE_ZOLTAN
149
150
151
    int a = 0;
    char *b = NULL;
    float zoltanVersion = 0.0;
152
    Zoltan_Initialize(a, &b, &zoltanVersion);
Thomas Witkowski's avatar
Thomas Witkowski committed
153
#endif
154

155
156
    elObjects.setFeSpace(feSpace);

157
158
159
    // 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).
160
    if (deserialized) {
161
162
      updateMacroElementInfo();

163
      setRankDofs();
164

165
      removePeriodicBoundaryConditions();
166

167
168
      macroElIndexMap.clear();
      macroElIndexTypeMap.clear();
169

170
      for (vector<MacroElement*>::iterator it = allMacroElements.begin();
171
	   it != allMacroElements.end(); ++it) {
172
173
174
175
	macroElIndexMap[(*it)->getIndex()] = (*it)->getElement();
	macroElIndexTypeMap[(*it)->getIndex()] = (*it)->getElType();
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
176
#if (DEBUG != 0)
177
      ParallelDebug::writeDebugFile(*this, debugOutputDir + "mpi-dbg", "dat");
Thomas Witkowski's avatar
Thomas Witkowski committed
178
#endif    
179
180

      initialized = true;
181
      return;
182
    }
183

184

185
186
187
188
189
    // 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();

190
191
192
193
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

194
    // create an initial partitioning of the mesh
195
    partitioner->createInitialPartitioning();
196

197
    // set the element weights, which are 1 at the very first begin
198
    setInitialElementWeights();
199
200

    // and now partition the mesh    
201
202
    bool partitioningSucceed = partitioner->partition(elemWeights, INITIAL);
    TEST_EXIT(partitioningSucceed)("Initial partitioning does not work!\n");
203
    partitioner->createPartitionMap(partitionMap);
204

205

206
#if (DEBUG != 0)    
207
208
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
209
210
    if (mpiRank == 0) {
      int writePartMesh = 1;
211
      Parameters::get("dbg->write part mesh", writePartMesh);
212

213
      if (writePartMesh > 0) {
214
	debug::writeElementIndexMesh(mesh, debugOutputDir + "elementIndex.vtu");
215
	ParallelDebug::writePartitioning(*this, debugOutputDir + "part.vtu");
216
      }
217
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
218
#endif
219

220

221
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
222

223
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
224

225
#if (DEBUG != 0)
226
    ParallelDebug::printBoundaryInfo(*this);
227
228
#endif

229
230
231
232
233
    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))) {
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
247
248
249
250
251
	}
      }
    }

    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))) {
252
253
254

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

255
256
257
258
259
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
260
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
261
262
263
	}
      }
    }
264

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
265
266
267
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
268

269
270
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
271

272
273
274
    // 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.
275
    for (map<BoundaryType, VertexVector*>::iterator it = mesh->getPeriodicAssociations().begin();
276
277
	 it != mesh->getPeriodicAssociations().end(); ++it)
      const_cast<DOFAdmin&>(mesh->getDofAdmin(0)).removeDOFContainer(dynamic_cast<DOFContainer*>(it->second));
278

279
    updateLocalGlobalNumbering();
280

281
282
283
284
285
286
    // === 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();

287
288
    // === If in debug mode, make some tests. ===

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

292
    ParallelDebug::testAllElements(*this);
293
    debug::testSortedDofs(mesh, elMap);
294
    ParallelDebug::testInteriorBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
295

296
    debug::writeMesh(feSpace, -1, debugOutputDir + "macro_mesh");   
297
298

    MSG("Debug mode tests finished!\n");
299
#endif
300

301
    // === Create periodic DOF mapping, if there are periodic boundaries. ===
302

303
    createPeriodicMap();
304

305
306
307
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
308

309
    // === Global refinements. ===
310
    
Thomas Witkowski's avatar
Thomas Witkowski committed
311
    int globalRefinement = 0;
312
    Parameters::get(mesh->getName() + "->global refinements", globalRefinement);
313
    
Thomas Witkowski's avatar
Thomas Witkowski committed
314
    if (globalRefinement > 0) {
315
      refineManager->globalRefine(mesh, globalRefinement);
316

317
      updateLocalGlobalNumbering();
318
319

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

322
      createPeriodicMap();
323
324
325
326

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

329

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

332
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
333

334

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

337
    removePeriodicBoundaryConditions();
338
339

    initialized = true;
340
341
  }

342

343
  void MeshDistributor::addProblemStat(ProblemStatSeq *probStat)
344
  {
345
    FUNCNAME("MeshDistributor::addProblemStat()");
346
347

    if (feSpace != NULL) {
348
      vector<FiniteElemSpace*> feSpaces = probStat->getFeSpaces();
349
350
351
352
353
      for (unsigned int i = 0; i < feSpaces.size(); i++) {
	TEST_EXIT(feSpace == feSpaces[i])
	  ("Parallelizaton is not supported for multiple FE spaces!\n");
      }
    } else {
354
      feSpace = probStat->getFeSpace(0);
355
      mesh = feSpace->getMesh();
356
      info = probStat->getInfo();
357
358
359
      
      TEST_EXIT(mesh->getNumberOfDOFAdmin() == 1)
	("Only meshes with one DOFAdmin are supported!\n");
360
      TEST_EXIT(mesh->getDofAdmin(0).getNumberOfPreDofs(VERTEX) == 0)
361
362
363
364
365
366
367
368
369
370
371
372
373
	("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());
      }

374
      partitioner->setMesh(mesh);
375
376
377
378
    }

    // Create parallel serialization file writer, if needed.
    int writeSerialization = 0;
379
    Parameters::get(probStat->getName() + "->output->write serialization",  
380
		    writeSerialization);
381
    if (writeSerialization && !writeSerializationFile) {
382
      string filename = "";
383
      Parameters::get(name + "->output->serialization filename", filename);
384
385
386
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel serialization file!\n");
387
388

      int tsModulo = -1;
389
      Parameters::get(probStat->getName() + "->output->write every i-th timestep", 
390
		      tsModulo);
391
      
392
      probStat->getFileWriterList().push_back(new Serializer<MeshDistributor>(this, filename, tsModulo));
393
394
      writeSerializationFile = true;
    }    
395
396

    int readSerialization = 0;
397
    Parameters::get(probStat->getName() + "->input->read serialization", 
398
		    readSerialization);
399
    if (readSerialization) {
400
      string filename = "";
401
      Parameters::get(probStat->getName() + "->input->serialization filename", 
402
		      filename);
403
      filename += ".p" + lexical_cast<string>(mpiRank);
404
      MSG("Start deserialization with %s\n", filename.c_str());
405
      ifstream in(filename.c_str());
406
407
408
409

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

410
      probStat->deserialize(in);
411
      in.close();
412
413
      MSG("Deserialization from file: %s\n", filename.c_str());

414
      filename = "";
415
      Parameters::get(name + "->input->serialization filename", filename);
416
417
418
419
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel deserialization file!\n");
      
420
      string rankFilename = filename + ".p" + lexical_cast<string>(mpiRank);
421
422
423
424
425
426
427
428
429
      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;
430
431
    }

432
    problemStat.push_back(probStat);
433
434
435
436
437

    // If the mesh distributor is already initialized, don't forgett to set rank
    // DOFs object to the matrices and vectors of the added stationary problem.

    if (initialized)
438
      setRankDofs(probStat);
439
440
441
  }


442
443
444
445
446
447
448
449
450
451
452
  void MeshDistributor::addProblemStatGlobal(ProblemStatSeq *probStat)
  {
    FUNCNAME("MeshDistributor::addProblemStatGlobal()");

    if (globalMeshDistributor == NULL)
      globalMeshDistributor = new MeshDistributor();

    globalMeshDistributor->addProblemStat(probStat);
  }


453
  void MeshDistributor::exitParallelization()
454
  {}
455

456
  
457
  void MeshDistributor::testForMacroMesh()
458
  {
459
    FUNCNAME("MeshDistributor::testForMacroMesh()");
460
461
462
463
464
465
466

    int nMacroElements = 0;

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

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
471
472
473
474
475
476
477
478
479
480
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

481

482
  void MeshDistributor::synchVector(DOFVector<double> &vec)
483
  {
484
    StdMpi<vector<double> > stdMpi(mpiComm);
485
486

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
487
	 sendIt != sendDofs.end(); ++sendIt) {
488
      vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
489
490
      int nSendDofs = sendIt->second.size();
      dofs.reserve(nSendDofs);
491
      
Thomas Witkowski's avatar
Thomas Witkowski committed
492
493
      for (int i = 0; i < nSendDofs; i++)
	dofs.push_back(vec[*((sendIt->second)[i])]);
494
495
496
497

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

Thomas Witkowski's avatar
Thomas Witkowski committed
498
499
500
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first, recvIt->second.size());
501

502
    stdMpi.startCommunication();
503

Thomas Witkowski's avatar
Thomas Witkowski committed
504
505
506
507
508
    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];
  }
509
510


511
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
512
  {
513
    int nComponents = vec.getSize();
514
    StdMpi<vector<double> > stdMpi(mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
515
516
517

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
	 sendIt != sendDofs.end(); ++sendIt) {
518
      vector<double> dofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
519
520
521
522
523
524
525
      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])]);
526
527
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
528
      stdMpi.send(sendIt->first, dofs);
529
530
531
    }

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

535
    stdMpi.startCommunication();
536
537

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
Thomas Witkowski's avatar
Thomas Witkowski committed
538
539
	 recvIt != recvDofs.end(); ++recvIt) {
      int nRecvDofs = recvIt->second.size();
540
541

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
542
543
544
545
546
      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++];
547
548
549
550
      }
    }
  }

551

552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
  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);
    }

575
576

    FixRefinementPatch::connectedEdges.clear();
577
    bool valid3dMesh = true;
578
579
580
581
582
583
584
585

    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;
586
587
588
589
      std::map<int, int> edgeNoInEl;

      for (unsigned int i = 0; i < edgeEls.size(); i++) {
	if (rankMacroEls.count(edgeEls[i].elIndex)) {
590
591
592
593
	  if (el0.empty())
	    el0.insert(edgeEls[i].elIndex);
	  else
	    el1.insert(edgeEls[i].elIndex);
594
595
596
597

	  edgeNoInEl[edgeEls[i].elIndex] = edgeEls[i].ithObject;
	}
      }
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
            
      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()) {
623
624
625
626
	valid3dMesh = false;

	MSG_DBG("Unvalid 3D mesh with %d (%d - %d) elements on this edge!\n", 
		edgeEls.size(), el0.size(), el1.size());
627

628
629
630
631
632
633
634
	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");
635

636
637
638
639
640
641
642
643
644
645
646
647
	    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);

648
649
650
651
	    MSG_DBG("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]);
652
653
654
655
656
657
658
659
660

	    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));
	  }
	}
      }
    }
661
662

    MSG_DBG("Mesh is 3d valid mesh: %d\n", valid3dMesh);
663
664
665
  }


666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
  void MeshDistributor::getAllBoundaryDofs(DofContainer& dofs)
  {
    FUNCNAME("MeshDistributor::getAllBoundaryDofs()");

    DofContainerSet dofSet;

    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
	 sendIt != sendDofs.end(); ++sendIt)
      for (DofContainer::iterator dofIt = sendIt->second.begin();
	   dofIt != sendIt->second.end(); ++dofIt)
	dofSet.insert(*dofIt);

    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt)
      for (DofContainer::iterator dofIt = recvIt->second.begin();
	   dofIt != recvIt->second.end(); ++dofIt)
	dofSet.insert(*dofIt);
    
    dofs.clear();
    dofs.insert(dofs.begin(), dofSet.begin(), dofSet.end());
  }


689
  void MeshDistributor::setRankDofs(ProblemStatSeq *probStat)
690
  {
691
    int nComponents = probStat->getNumComponents();
692
693
    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++)
694
695
	if (probStat->getSystemMatrix(i, j))
	  probStat->getSystemMatrix(i, j)->setRankDofs(isRankDof);
696

697
      TEST_EXIT_DBG(probStat->getRhs()->getDOFVector(i))("No RHS vector!\n");
698
699
      TEST_EXIT_DBG(probStat->getSolution()->getDOFVector(i))
	("No solution vector!\n");
700
      
701
702
      probStat->getRhs()->getDOFVector(i)->setRankDofs(isRankDof);
      probStat->getSolution()->getDOFVector(i)->setRankDofs(isRankDof);
703
704
705
706
    }    
  }


707
708
  void MeshDistributor::setRankDofs()
  {
709
710
    for (unsigned int i = 0; i < problemStat.size(); i++) 
      setRankDofs(problemStat[i]);
711
712
713
  }


714
715
  void MeshDistributor::removePeriodicBoundaryConditions()
  {
716
717
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

718
    // Remove periodic boundaries in boundary manager on matrices and vectors.
719
720
    for (unsigned int i = 0; i < problemStat.size(); i++) {
      int nComponents = problemStat[i]->getNumComponents();
721
722
723

      for (int j = 0; j < nComponents; j++) {
	for (int k = 0; k < nComponents; k++) {
724
	  DOFMatrix* mat = problemStat[i]->getSystemMatrix(j, k);
725
	  if (mat && mat->getBoundaryManager())
726
	    removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
727
728
	}
	
729
730
	if (problemStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(problemStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
731
	
732
733
	if (problemStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(problemStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
734
735
736
737
738
739
740
741
742
743
      }
    }

    // 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);
    }    
744
745
746

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
747
748
749
750
  }


  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
751
752
753
754
755
756
757
758
759
760
761
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


762
  void MeshDistributor::checkMeshChange(bool tryRepartition)
763
  {
764
    FUNCNAME("MeshDistributor::checkMeshChange()");
765

766
767
    double first = MPI::Wtime();

768
769
770
771
772
    // === 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);
773

774
    if (recvAllValues == 0)
775
776
      return;

777
778
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
779
   
780
    do {
781
782
      bool meshChanged = false;

783
784
      // To check the interior boundaries, the ownership of the boundaries is not 
      // important. Therefore, we add all boundaries to one boundary container.
785
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
786
787

      for (InteriorBoundary::iterator it(myIntBoundary); !it.end(); ++it)
788
789
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
790
 	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
791
792

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

797
798
      for (InteriorBoundary::iterator it(periodicBoundary); !it.end(); ++it) {
	if (it.getRank() == mpiRank) {
799
800
801
802
803
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE)) {
	    MeshStructure elCode;
	    elCode.init(it->rankObj);
	    
804
	    MeshManipulation mm(feSpace);
805
	    meshChanged |= mm.fitElementToMeshCode(elCode, it->neighObj);
806
	  }
807
808
809
810
811
812
	} else {
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
	    allBound[it.getRank()].push_back(*it);	
	}
      }
813

814

815
      // === Check the boundaries and adapt mesh if necessary. ===
816
      MSG_DBG("Run checkAndAdaptBoundary ...\n");
817

818
      meshChanged |= checkAndAdaptBoundary(allBound);
819
820
821

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

822
      int sendValue = static_cast<int>(meshChanged);
823
824
      recvAllValues = 0;
      mpiComm.Allreduce(&sendValue, &recvAllValues, 1, MPI_INT, MPI_SUM);
825
826

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

829
#if (DEBUG != 0)
830
    debug::writeMesh(feSpace, -1, debugOutputDir + "mesh");
831
832
#endif

833

834
    // === Because the mesh has been changed, update the DOF numbering and mappings. ===
835

836
837
    updateLocalGlobalNumbering();

838

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

Thomas Witkowski's avatar
Thomas Witkowski committed
841
    createPeriodicMap();
842

843
844
845
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
846
847


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

850
    nMeshChangesAfterLastRepartitioning++;
851

852
853
854
855

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

856
857
    if (tryRepartition &&
	repartitioningAllowed && 
858
859
860
	nMeshChangesAfterLastRepartitioning >= repartitionIthChange) {
      repartitionMesh();
      nMeshChangesAfterLastRepartitioning = 0;
861
862
863
864
    } else {
      MSG_DBG("Repartitioning not tried because tryRepartitioning = %d   reparttitioningAllowed = %d   nMeshChange =%d    repartitionIthChange = %d\n",
	      tryRepartition, repartitioningAllowed, 
	      nMeshChangesAfterLastRepartitioning, repartitionIthChange);
865
    }
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884

    // === 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);
    }
885
886
887
  }

  
888
  bool MeshDistributor::checkAndAdaptBoundary(RankToBoundMap &allBound)
889
  {
890
    FUNCNAME("MeshDistributor::checkAndAdaptBoundary()");
891
892
893

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

898
      for (vector<AtomicBoundary>::iterator boundIt = it->second.begin();
899
900
	   boundIt != it->second.end(); ++boundIt) {
	MeshStructure elCode;
901
	elCode.init(boundIt->rankObj);
902
903
904
905
	sendCodes[it->first].push_back(elCode);
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
906
    StdMpi<MeshCodeVec> stdMpi(mpiComm, true);
907
    stdMpi.send(sendCodes);
908
909
910
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it)
      stdMpi.recv(it->first);
    stdMpi.startCommunication();
911
 
912
    // === Compare received mesh structure codes. ===
913
    
914
    bool meshChanged = false;
915

916
    for (RankToBoundMap::iterator it = allBound.begin(); it != allBound.end(); ++it) {
917