MeshDistributor.cc 77 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
      feSpaces(0),
75
76
77
78
      mesh(NULL),
      refineManager(NULL),
      info(10),
      partitioner(NULL),
79
      deserialized(false),
80
      writeSerializationFile(false),
81
      repartitioningAllowed(false),
82
      repartitionIthChange(20),
83
84
      nMeshChangesAfterLastRepartitioning(0),
      repartitioningCounter(0),
85
      debugOutputDir(""),
Thomas Witkowski's avatar
Thomas Witkowski committed
86
87
      lastMeshChangeIndex(0),
      createBoundaryDofFlag(0)
88
  {
89
    FUNCNAME("MeshDistributor::ParalleDomainBase()");
Thomas Witkowski's avatar
Thomas Witkowski committed
90

91
92
93
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
94
95

    int tmp = 0;
96
    Parameters::get(name + "->repartitioning", tmp);
97
    repartitioningAllowed = (tmp > 0);
98

99
100
    Parameters::get(name + "->debug output dir", debugOutputDir);
    Parameters::get(name + "->repartition ith change", repartitionIthChange);
101
102

    tmp = 0;
103
    Parameters::get(name + "->log main rank", tmp);
104
    Msg::outputMainRank = (tmp > 0);
105

106
    string partStr = "parmetis";
107
    Parameters::get(name + "->partitioner", partStr);
108
109
110
111

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

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

120
121
122
    if (partStr == "checker")
      partitioner = new CheckerPartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
123
124
125
    if (partStr == "simple")
      partitioner = new SimplePartitioner(&mpiComm);

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

130
    TEST_EXIT(partitioner)("Could not create partitioner \"%s\"!\n", partStr.c_str());
131
132
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
133

134
  void MeshDistributor::initParallelization()
135
  {
136
    FUNCNAME("MeshDistributor::initParallelization()");
137

138
139
140
    if (initialized)
      return;

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

144
145
    TEST_EXIT(feSpaces.size() > 0)
      ("No FE space has been defined for the mesh distributor!\n");
146
    TEST_EXIT(mesh)("No mesh has been defined for the mesh distributor!\n");
147

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    // === Sort FE spaces with respect to the degree of the basis ===
    // === functions. Use stuiped bubble sort for this.           ===

    bool doNext = false;
    do {
      for (unsigned int i = 0; i < feSpaces.size() - 1; i++)
	if (feSpaces[i]->getBasisFcts()->getDegree() >
	    feSpaces[i + 1]->getBasisFcts()->getDegree()) {
	  const FiniteElemSpace *tmp = feSpaces[i + 1];
	  feSpaces[i + 1] = feSpaces[i];
	  feSpaces[i] = tmp;
	  doNext = true;
	}
    } while (doNext);

    elObjects.setMesh(feSpaces[0]->getMesh());
164

165
166
167
    // 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).
168
    if (deserialized) {
169
170
      updateMacroElementInfo();

171
      setRankDofs();
172

173
      removePeriodicBoundaryConditions();
174

175
176
      macroElIndexMap.clear();
      macroElIndexTypeMap.clear();
177

178
      for (vector<MacroElement*>::iterator it = allMacroElements.begin();
179
	   it != allMacroElements.end(); ++it) {
180
181
182
183
	macroElIndexMap[(*it)->getIndex()] = (*it)->getElement();
	macroElIndexTypeMap[(*it)->getIndex()] = (*it)->getElType();
      }

184
185
      createBoundaryDofs();

Thomas Witkowski's avatar
Thomas Witkowski committed
186
#if (DEBUG != 0)
187
      ParallelDebug::writeDebugFile(*this, debugOutputDir + "mpi-dbg", "dat");
Thomas Witkowski's avatar
Thomas Witkowski committed
188
#endif    
189
190

      initialized = true;
191
      return;
192
    }
193

194

195
196
197
198
199
    // 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();

200
201
202
203
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

204
    // create an initial partitioning of the mesh
205
    partitioner->createInitialPartitioning();
206

207
    // set the element weights, which are 1 at the very first begin
208
    setInitialElementWeights();
209
210

    // and now partition the mesh    
211
212
    bool partitioningSucceed = partitioner->partition(elemWeights, INITIAL);
    TEST_EXIT(partitioningSucceed)("Initial partitioning does not work!\n");
213
    partitioner->createPartitionMap(partitionMap);
214

215

216
#if (DEBUG != 0)    
217
218
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
219
220
#endif

221
    if (mpiRank == 0) {
222
#if (DEBUG != 0)    
223
      int writePartMesh = 1;
224
225
226
#else
      int writePartMesh = 0;
#endif
227
      Parameters::get("dbg->write part mesh", writePartMesh);
228

229
      if (writePartMesh > 0) {
230
	debug::writeElementIndexMesh(mesh, debugOutputDir + "elementIndex.vtu");
231
	ParallelDebug::writePartitioning(*this, debugOutputDir + "part.vtu");
232
      }
233
    }
234

235

236
    // === Create interior boundary information. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
237

238
    createInteriorBoundaryInfo();
Thomas Witkowski's avatar
Thomas Witkowski committed
239

240
#if (DEBUG != 0)
241
    ParallelDebug::printBoundaryInfo(*this);
242
243
#endif

244
245
246
    
    // === Remove neighbourhood relations due to periodic bounday conditions. ===

247
248
249
250
251
    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))) {
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
265
266
267
268
269
	}
      }
    }

    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))) {
270
271
272

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

273
274
275
276
277
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
278
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
279
280
281
	}
      }
    }
282

Thomas Witkowski's avatar
n  
Thomas Witkowski committed
283
284
285
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
286

287
288
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
289

290
291
292
    // 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.
293
    for (map<BoundaryType, VertexVector*>::iterator it = mesh->getPeriodicAssociations().begin();
294
295
	 it != mesh->getPeriodicAssociations().end(); ++it)
      const_cast<DOFAdmin&>(mesh->getDofAdmin(0)).removeDOFContainer(dynamic_cast<DOFContainer*>(it->second));
296

297
    updateLocalGlobalNumbering();
298

299
300
301
302
303
304
    // === 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();

305
306
    // === If in debug mode, make some tests. ===

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

310
    ParallelDebug::testAllElements(*this);
311
    debug::testSortedDofs(mesh, elMap);
312
    ParallelDebug::testInteriorBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
313
    ParallelDebug::followBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
314

315
    debug::writeMesh(feSpaces[0], -1, debugOutputDir + "macro_mesh");   
316
317

    MSG("Debug mode tests finished!\n");
318
#endif
319

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

322
    createPeriodicMap(feSpaces[0]);
323

324
325
326
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
327

328
    // === Global refinements. ===
329
    
Thomas Witkowski's avatar
Thomas Witkowski committed
330
    int globalRefinement = 0;
331
    Parameters::get(mesh->getName() + "->global refinements", globalRefinement);
332
    
Thomas Witkowski's avatar
Thomas Witkowski committed
333
    if (globalRefinement > 0) {
334
      refineManager->globalRefine(mesh, globalRefinement);
335

336
      updateLocalGlobalNumbering();
337
338

     
339
340
      // === Update periodic mapping, if there are periodic boundaries. ===     

341
      createPeriodicMap(feSpaces[0]);
342
343
344
345

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

348

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

351
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
352

353

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

356
    removePeriodicBoundaryConditions();
357
358

    initialized = true;
359
360
  }

361

362
  void MeshDistributor::addProblemStat(ProblemStatSeq *probStat)
363
  {
364
    FUNCNAME("MeshDistributor::addProblemStat()");
365

366
367
368
369
370
371
372
373
374
375
    // === Add FE spaces from stationary problem to mesh distributor. ===

    for (unsigned int i = 0; i < probStat->getFeSpaces().size(); i++) {
      bool foundFeSpace = false;
      for (unsigned int j = 0; j < feSpaces.size(); j++) {
	if (feSpaces[j] == probStat->getFeSpaces()[i])
	  foundFeSpace = true;

	TEST_EXIT(feSpaces[j]->getMesh() == probStat->getFeSpaces()[i]->getMesh())
	  ("MeshDistributor does not yet support usage of different meshes!\n");
376
377
      }

378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
      if (!foundFeSpace)
	feSpaces.push_back(probStat->getFeSpaces()[i]);
    }

    TEST_EXIT(feSpaces.size() > 0)("Should not happen!\n");

    mesh = feSpaces[0]->getMesh();
    info = probStat->getInfo();
    
    TEST_EXIT(mesh->getNumberOfDOFAdmin() == 1)
      ("Only meshes with one DOFAdmin are supported!\n");
    TEST_EXIT(mesh->getDofAdmin(0).getNumberOfPreDofs(VERTEX) == 0)
      ("Wrong pre dof number for DOFAdmin!\n");
    
    switch (mesh->getDim()) {
    case 2:
      refineManager = new RefinementManager2d();
      break;
    case 3:
      refineManager = new RefinementManager3d();
      break;
    default:
      ERROR_EXIT("This should not happen for dim = %d!\n", mesh->getDim());
401
    }
402
403
404
    
    partitioner->setMesh(mesh);
    
405
406
407

    // Create parallel serialization file writer, if needed.
    int writeSerialization = 0;
408
    Parameters::get(probStat->getName() + "->output->write serialization",  
409
		    writeSerialization);
410
    if (writeSerialization && !writeSerializationFile) {
411
      string filename = "";
412
      Parameters::get(name + "->output->serialization filename", filename);
413
414
415
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel serialization file!\n");
416
417

      int tsModulo = -1;
418
      Parameters::get(probStat->getName() + "->output->write every i-th timestep", 
419
		      tsModulo);
420
      
421
      probStat->getFileWriterList().push_back(new Serializer<MeshDistributor>(this, filename, tsModulo));
422
423
      writeSerializationFile = true;
    }    
424
425

    int readSerialization = 0;
426
    Parameters::get(probStat->getName() + "->input->read serialization", 
427
		    readSerialization);
428
    if (readSerialization) {
429
      string filename = "";
430
      Parameters::get(probStat->getName() + "->input->serialization filename", 
431
		      filename);
432
      filename += ".p" + lexical_cast<string>(mpiRank);
433
      MSG("Start deserialization with %s\n", filename.c_str());
434
      ifstream in(filename.c_str());
435
436
437
438

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

439
440
441
442
443
      // Read the revision number of the AMDiS version which was used to create 
      // the serialization file.
      int revNumber = -1;
      SerUtil::deserialize(in, revNumber);

444
      probStat->deserialize(in);
445
      in.close();
446
447
      MSG("Deserialization from file: %s\n", filename.c_str());

448
      filename = "";
449
      Parameters::get(name + "->input->serialization filename", filename);
450
451
452
453
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel deserialization file!\n");
      
454
      string rankFilename = filename + ".p" + lexical_cast<string>(mpiRank);
455
456
457
458
      in.open(rankFilename.c_str());
      
      TEST_EXIT(!in.fail())("Could not open parallel deserialization file: %s\n",
			    filename.c_str());
459
460
461
462
463

      // Read the revision number of the AMDiS version which was used to create 
      // the serialization file.
      revNumber = -1;
      SerUtil::deserialize(in, revNumber);
464
465
466
467
468
      
      deserialize(in);
      in.close();
      MSG("Deserializtion of mesh distributor from file: %s\n", rankFilename.c_str());
      deserialized = true;
469
470
    }

471
    problemStat.push_back(probStat);
472
473
474
475
476

    // 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)
477
      setRankDofs(probStat);
478
479
480
  }


481
482
483
484
485
486
487
488
489
490
491
  void MeshDistributor::addProblemStatGlobal(ProblemStatSeq *probStat)
  {
    FUNCNAME("MeshDistributor::addProblemStatGlobal()");

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

    globalMeshDistributor->addProblemStat(probStat);
  }


492
  void MeshDistributor::exitParallelization()
493
  {}
494

495
  
496
  void MeshDistributor::testForMacroMesh()
497
  {
498
    FUNCNAME("MeshDistributor::testForMacroMesh()");
499
500
501
502
503
504
505

    int nMacroElements = 0;

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

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
510
511
512
513
514
515
516
517
518
519
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

520

521
  void MeshDistributor::synchVector(SystemVector &vec)
Thomas Witkowski's avatar
Thomas Witkowski committed
522
  {
523
524
    FUNCNAME("MeshDistributor::synchVector()");

525
    int nComponents = vec.getSize();
526
    StdMpi<vector<double> > stdMpi(mpiComm);
Thomas Witkowski's avatar
Thomas Witkowski committed
527

528
529
530
    typedef map<int, map<const FiniteElemSpace*, DofContainer> >::iterator it_type;

    for (it_type sendIt = sendDofs.begin(); sendIt != sendDofs.end(); ++sendIt) {
531
      vector<double> dofs;
532

Thomas Witkowski's avatar
Thomas Witkowski committed
533
      for (int i = 0; i < nComponents; i++) {
534
535
536
	TEST_EXIT_DBG(sendIt->second.count(vec.getFeSpace(i)))
	  ("Should not happen!\n");

537
538
539
540
541
542
543
	DofContainer &feDofs = sendIt->second[vec.getFeSpace(i)];
	DOFVector<double>& dofVec = *(vec.getDOFVector(i));

	int nFeDofs = feDofs.size();
	for (int j = 0; j < nFeDofs; j++) 
	  dofs.push_back(dofVec[*(feDofs[j])]);
      }	
544

Thomas Witkowski's avatar
Thomas Witkowski committed
545
      stdMpi.send(sendIt->first, dofs);
546
547
    }

548
549
    for (it_type recvIt = recvDofs.begin(); recvIt != recvDofs.end(); ++recvIt)
      stdMpi.recv(recvIt->first);
550

551
    stdMpi.startCommunication();
552

553
    for (it_type recvIt = recvDofs.begin(); recvIt != recvDofs.end(); ++recvIt) {
554
555

      int counter = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
556
      for (int i = 0; i < nComponents; i++) {
557
558
559
560
561
562
	DofContainer &feDofs = recvIt->second[vec.getFeSpace(i)];
	DOFVector<double>& dofVec = *(vec.getDOFVector(i));
	int nFeDofs = feDofs.size();
	
	for (int j = 0; j < nFeDofs; j++)
	  dofVec[*(feDofs[j])] = stdMpi.getRecvData(recvIt->first)[counter++];
563
564
565
566
      }
    }
  }

567

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
  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);
    }

591
592

    FixRefinementPatch::connectedEdges.clear();
593
    bool valid3dMesh = true;
594
595
596
597
598
599
600
601

    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;
602
      map<int, int> edgeNoInEl;
603
604
605

      for (unsigned int i = 0; i < edgeEls.size(); i++) {
	if (rankMacroEls.count(edgeEls[i].elIndex)) {
606
607
608
609
	  if (el0.empty())
	    el0.insert(edgeEls[i].elIndex);
	  else
	    el1.insert(edgeEls[i].elIndex);
610
611
612
613

	  edgeNoInEl[edgeEls[i].elIndex] = edgeEls[i].ithObject;
	}
      }
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
            
      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()) {
639
640
641
642
	valid3dMesh = false;

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

644
645
646
647
648
649
650
	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");
651

652
653
654
655
656
657
658
659
660
	    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;
661
662
	    mesh->getDofIndexCoords(dofEdge0.first, feSpaces[0], c0);
	    mesh->getDofIndexCoords(dofEdge0.second, feSpaces[0], c1);
663

664
665
666
667
	    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]);
668
669
670
671
672
673
674
675
676

	    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));
	  }
	}
      }
    }
677
678

    MSG_DBG("Mesh is 3d valid mesh: %d\n", valid3dMesh);
679
680
681
  }


682
683
  void MeshDistributor::getAllBoundaryDofs(const FiniteElemSpace *feSpace,
					   DofContainer& dofs)
684
685
686
687
688
  {
    FUNCNAME("MeshDistributor::getAllBoundaryDofs()");

    DofContainerSet dofSet;

689
    typedef map<int, map<const FiniteElemSpace*, DofContainer> >::iterator it_type;
690

691
692
693
694
695
    for (it_type it = sendDofs.begin(); it != sendDofs.end(); ++it)
      dofSet.insert(it->second[feSpace].begin(), it->second[feSpace].end());

    for (it_type it = recvDofs.begin(); it != recvDofs.end(); ++it)
      dofSet.insert(it->second[feSpace].begin(), it->second[feSpace].end());
696
697
698
699
700
701
    
    dofs.clear();
    dofs.insert(dofs.begin(), dofSet.begin(), dofSet.end());
  }


702
  void MeshDistributor::setRankDofs(ProblemStatSeq *probStat)
703
  {
704
705
    FUNCNAME("MeshDistributor::setRankDofs()");

706
    int nComponents = probStat->getNumComponents();
707
708
    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++)
709
710
711
712
713
714
715
716
717
718
	if (probStat->getSystemMatrix(i, j)) {
	  const FiniteElemSpace *rowFeSpace = 
	    probStat->getSystemMatrix(i, j)->getRowFeSpace();

	  TEST_EXIT(find(feSpaces.begin(), feSpaces.end(), rowFeSpace) != feSpaces.end())
	    ("Should not happen!\n");

	  probStat->getSystemMatrix(i, j)->setRankDofs(dofFeData[rowFeSpace].isRankDof);
	}
    
719

720
      TEST_EXIT_DBG(probStat->getRhs()->getDOFVector(i))("No RHS vector!\n");
721
722
      TEST_EXIT_DBG(probStat->getSolution()->getDOFVector(i))
	("No solution vector!\n");
723
724
725
      TEST_EXIT_DBG(probStat->getRhsVector(i)->getFeSpace() ==
		    probStat->getSolution(i)->getFeSpace())
	("Should not happen!\n");
726
      
727
728
729
730
731
732
      const FiniteElemSpace *feSpace = probStat->getRhsVector(i)->getFeSpace();
      TEST_EXIT(find(feSpaces.begin(), feSpaces.end(), feSpace) != feSpaces.end())
	("Should not happen!\n");

      probStat->getRhsVector(i)->setRankDofs(dofFeData[feSpace].isRankDof);
      probStat->getSolution(i)->setRankDofs(dofFeData[feSpace].isRankDof);
733
734
735
736
    }    
  }


737
738
  void MeshDistributor::setRankDofs()
  {
739
740
    for (unsigned int i = 0; i < problemStat.size(); i++) 
      setRankDofs(problemStat[i]);
741
742
743
  }


744
745
  void MeshDistributor::removePeriodicBoundaryConditions()
  {
746
747
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

748
    // Remove periodic boundaries in boundary manager on matrices and vectors.
749
750
    for (unsigned int i = 0; i < problemStat.size(); i++) {
      int nComponents = problemStat[i]->getNumComponents();
751
752
753

      for (int j = 0; j < nComponents; j++) {
	for (int k = 0; k < nComponents; k++) {
754
	  DOFMatrix* mat = problemStat[i]->getSystemMatrix(j, k);
755
	  if (mat && mat->getBoundaryManager())
756
	    removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
757
758
	}
	
759
760
	if (problemStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(problemStat[i]->getSolution()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
761
	
762
763
	if (problemStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(problemStat[i]->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
764
765
766
767
768
769
770
771
772
773
      }
    }

    // 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);
    }    
774
775
776

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
777
778
779
780
  }


  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
781
782
783
784
785
786
787
788
789
790
791
  {
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
      if (it->second->isPeriodic())
	boundaryMap.erase(it++);
      else
	++it;      
    }    
  }


792
  void MeshDistributor::checkMeshChange(bool tryRepartition)
793
  {
794
    FUNCNAME("MeshDistributor::checkMeshChange()");
795

796
797
    double first = MPI::Wtime();

798
799
800
801
802
    // === 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);
803

804
    if (recvAllValues == 0)
805
806
      return;

807
808
    // === At least one rank mesh has been changed, so the boundaries must be ===
    // === adapted to the new mesh structure.                                 ===
809
   
810
    do {
811
812
      bool meshChanged = false;

813
814
      // To check the interior boundaries, the ownership of the boundaries is not 
      // important. Therefore, we add all boundaries to one boundary container.
815
      RankToBoundMap allBound;
Thomas Witkowski's avatar
Thomas Witkowski committed
816
817

      for (InteriorBoundary::iterator it(myIntBoundary); !it.end(); ++it)
818
819
	if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	    (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
820
 	  allBound[it.getRank()].push_back(*it);
Thomas Witkowski's avatar
Thomas Witkowski committed
821
822

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

827
828
      for (InteriorBoundary::iterator it(periodicBoundary); !it.end(); ++it) {
	if (it.getRank() == mpiRank) {
829
830
831
832
833
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE)) {
	    MeshStructure elCode;
	    elCode.init(it->rankObj);
	    
834
	    MeshManipulation mm(mesh);
835
	    meshChanged |= mm.fitElementToMeshCode(elCode, it->neighObj);
836
	  }
837
838
839
840
841
842
	} else {
	  if ((mesh->getDim() == 2 && it->rankObj.subObj == EDGE) || 
	      (mesh->getDim() == 3 && it->rankObj.subObj == FACE))
	    allBound[it.getRank()].push_back(*it);	
	}
      }
843

844

845
      // === Check the boundaries and adapt mesh if necessary. ===
846
      MSG_DBG("Run checkAndAdaptBoundary ...\n");
847

848
      meshChanged |= checkAndAdaptBoundary(allBound);
849
850
851

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

852
      int sendValue = static_cast<int>(meshChanged);
853
854
      recvAllValues = 0;
      mpiComm.Allreduce(&sendValue, &recvAllValues, 1, MPI_INT, MPI_SUM);
855
856

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

859
#if (DEBUG != 0)
860
    debug::writeMesh(feSpaces[0], -1, debugOutputDir + "mesh");
861
862
#endif

863

864
    // === Because the mesh has been changed, update the DOF numbering and mappings. ===
865

866
867
    updateLocalGlobalNumbering();

868