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


Thomas Witkowski's avatar
Thomas Witkowski committed
13
#include <algorithm>
14
15
#include <iostream>
#include <fstream>
16
17
#include <limits>
#include <stdint.h>
Thomas Witkowski's avatar
Thomas Witkowski committed
18
#include <boost/lexical_cast.hpp>
19
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
#include "parallel/DofComm.h"
32
33
#include "io/ElementFileWriter.h"
#include "io/MacroInfo.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
34
#include "io/MacroWriter.h"
35
#include "io/VtkWriter.h"
36
37
38
39
40
#include "Mesh.h"
#include "Traverse.h"
#include "ElInfo.h"
#include "Element.h"
#include "MacroElement.h"
41
42
#include "DOFMatrix.h"
#include "DOFVector.h"
43
#include "SystemVector.h"
44
#include "ElementDofIterator.h"
45
46
#include "ProblemStatBase.h"
#include "StandardProblemIteration.h"
47
#include "VertexVector.h"
48
#include "MeshStructure.h"
49
#include "ProblemStat.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
50
#include "ProblemInstat.h"
51
#include "RefinementManager3d.h"
52
#include "Debug.h"
53

54
55
namespace AMDiS {

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

60
61
  MeshDistributor* MeshDistributor::globalMeshDistributor = NULL;

62
63
64
  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
65

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

71

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

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

98
    Parameters::get(name + "->repartitioning", repartitioningAllowed);
99
100
    Parameters::get(name + "->debug output dir", debugOutputDir);
    Parameters::get(name + "->repartition ith change", repartitionIthChange);
101
    Parameters::get(name + "->log main rank", Msg::outputMainRank);
102

103
    string partStr = "parmetis";
104
    Parameters::get(name + "->partitioner", partStr);
105
106
107
108

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

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

117
118
119
    if (partStr == "checker")
      partitioner = new CheckerPartitioner(&mpiComm);

Thomas Witkowski's avatar
Thomas Witkowski committed
120
121
122
    if (partStr == "simple")
      partitioner = new SimplePartitioner(&mpiComm);

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

127
    TEST_EXIT(partitioner)("Could not create partitioner \"%s\"!\n", partStr.c_str());
128
129
  }

Thomas Witkowski's avatar
Thomas Witkowski committed
130

131
  void MeshDistributor::initParallelization()
132
  {
133
    FUNCNAME("MeshDistributor::initParallelization()");
134

135
136
137
    if (initialized)
      return;

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

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

145
146
147
148
149
    // === Sort FE spaces with respect to the degree of the basis ===
    // === functions. Use stuiped bubble sort for this.           ===

    bool doNext = false;
    do {
150
151
      doNext = false;
      for (unsigned int i = 0; i < feSpaces.size() - 1; i++) {
152
153
154
155
156
157
158
	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;
	}
159
      }
160
161
    } while (doNext);

162
    elObjDb.setFeSpace(feSpaces[0]);
163

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

170
      setRankDofs();
171

172
      removePeriodicBoundaryConditions();
173

174
      elObjDb.createMacroElementInfo(allMacroElements);
175

176
177
      createBoundaryDofs();

Thomas Witkowski's avatar
Thomas Witkowski committed
178
#if (DEBUG != 0)
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
179
180
      ParallelDebug::writeDebugFile(feSpaces[feSpaces.size() - 1], dofMap, 
				    debugOutputDir + "mpi-dbg", "dat");
Thomas Witkowski's avatar
Thomas Witkowski committed
181
#endif    
182
183

      initialized = true;
184
      return;
185
    }
186

187

188
189
190
191
192
    // 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();

193
194
195
196
    // For later mesh repartitioning, we need to store some information about the
    // macro mesh.
    createMacroElementInfo();

197
    // create an initial partitioning of the mesh
198
    partitioner->createInitialPartitioning();
199

200
    // set the element weights, which are 1 at the very first begin
201
    setInitialElementWeights();
202
203

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

208

209
#if (DEBUG != 0)    
210
211
    debug::ElementIdxToDofs elMap;
    debug::createSortedDofs(mesh, elMap);
212
213
#endif

214
    if (mpiRank == 0) {
215
#if (DEBUG != 0)    
216
      int writePartMesh = 1;
217
218
219
#else
      int writePartMesh = 0;
#endif
220
      Parameters::get("dbg->write part mesh", writePartMesh);
221

222
      if (writePartMesh > 0) {
223
	debug::writeElementIndexMesh(mesh, debugOutputDir + "elementIndex.vtu");
224
	ParallelDebug::writePartitioning(*this, debugOutputDir + "part.vtu");
225
      }
226
    }
227

228
229
    // If required, create hierarchical mesh level structure.
    createMeshLevelStructure();
230

231
    // Create interior boundary information.
232
    createInteriorBoundary(true);
Thomas Witkowski's avatar
Thomas Witkowski committed
233

234
235
    // === Remove neighbourhood relations due to periodic bounday conditions. ===

236
237
238
239
240
    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))) {
241
242
243

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

244
245
246
247
248
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
249
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
250
251
252
253
254
255
256
257
258
	}
      }
    }

    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))) {
259
260
261

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

262
263
264
265
266
	  (*it)->getNeighbour(i)->setNeighbour((*it)->getOppVertex(i), NULL);
	  (*it)->setNeighbour(i, NULL);
	  (*it)->setBoundary(i, 0);

	  macroElementNeighbours[(*it)->getIndex()][i] = -1;
267
	  macroElementNeighbours[neighIndex][(*it)->getOppVertex(i)] = -1;
268

269
270
271
	}
      }
    }
272

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
273
274
275
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();
276

277
278
    // === Create new global and local DOF numbering. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
279

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

287
    updateLocalGlobalNumbering();
288

289
290
291
    // === 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.                         ===
292
293
294
    
    check3dValidMesh();

295
296
    // === If in debug mode, make some tests. ===

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

300
    ParallelDebug::testAllElements(*this);
301
    debug::testSortedDofs(mesh, elMap);
302
    ParallelDebug::testInteriorBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
303
    ParallelDebug::followBoundary(*this);
Thomas Witkowski's avatar
Thomas Witkowski committed
304

305
    debug::writeMesh(feSpaces[0], -1, debugOutputDir + "macro_mesh");   
306
307

    MSG("Debug mode tests finished!\n");
308
#endif
309

310
    // Create periodic DOF mapping, if there are periodic boundaries.
311
    createPeriodicMap();
312

313
314
315
    // Remove periodic boundary conditions in sequential problem definition. 
    removePeriodicBoundaryConditions();

316
317
318
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
319

320
    // === Global refinements. ===
321
    
Thomas Witkowski's avatar
Thomas Witkowski committed
322
    int globalRefinement = 0;
323
    Parameters::get(mesh->getName() + "->global refinements", globalRefinement);
324
    
Thomas Witkowski's avatar
Thomas Witkowski committed
325
    if (globalRefinement > 0) {
326
      refineManager->globalRefine(mesh, globalRefinement);
327

328
      updateLocalGlobalNumbering();
329

330
331
      // === Update periodic mapping, if there are periodic boundaries. ===     

332
      createPeriodicMap();
333
334
335
#if (DEBUG != 0)
    ParallelDebug::testPeriodicBoundary(*this);
#endif
Thomas Witkowski's avatar
Thomas Witkowski committed
336
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
337

338
    // Set DOF rank information to all matrices and vectors.
339
    setRankDofs();
Thomas Witkowski's avatar
Thomas Witkowski committed
340

341
    initialized = true;
342
343
  }

344

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

349
350
351
    TEST_EXIT_DBG(probStat->getFeSpaces().size())
      ("No FE spaces in stationary problem!\n");

352
353
354
355
356
357
358
359
360
361
    // === 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");
362
363
      }

364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
      if (!foundFeSpace)
	feSpaces.push_back(probStat->getFeSpaces()[i]);
    }

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

    mesh = feSpaces[0]->getMesh();
    info = probStat->getInfo();
    
    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());
382
    }
383
384
385
    
    partitioner->setMesh(mesh);
    
386
387
388

    // Create parallel serialization file writer, if needed.
    int writeSerialization = 0;
389
    Parameters::get(probStat->getName() + "->output->write serialization",  
390
		    writeSerialization);
391
    if (writeSerialization && !writeSerializationFile) {
392
      string filename = "";
393
      Parameters::get(name + "->output->serialization filename", filename);
394
395
396
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel serialization file!\n");
397
398

      int tsModulo = -1;
399
      Parameters::get(probStat->getName() + "->output->write every i-th timestep", 
400
		      tsModulo);
401
      
402
      probStat->getFileWriterList().push_back(new Serializer<MeshDistributor>(this, filename, tsModulo));
403
404
      writeSerializationFile = true;
    }    
405
406

    int readSerialization = 0;
407
    Parameters::get(probStat->getName() + "->input->read serialization", 
408
		    readSerialization);
409
    if (readSerialization) {
410
      string filename = "";
411
      Parameters::get(probStat->getName() + "->input->serialization filename", 
412
		      filename);
413
      filename += ".p" + lexical_cast<string>(mpiRank);
414
      MSG("Start deserialization with %s\n", filename.c_str());
415
      ifstream in(filename.c_str());
416
417
418
419

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

420
421
422
423
424
      // Read the revision number of the AMDiS version which was used to create 
      // the serialization file.
      int revNumber = -1;
      SerUtil::deserialize(in, revNumber);

425
      probStat->deserialize(in);
426
      in.close();
427
428
      MSG("Deserialization from file: %s\n", filename.c_str());

429
      filename = "";
430
      Parameters::get(name + "->input->serialization filename", filename);
431
432
433
434
      
      TEST_EXIT(filename != "")
	("No filename defined for parallel deserialization file!\n");
      
435
      string rankFilename = filename + ".p" + lexical_cast<string>(mpiRank);
436
437
438
439
      in.open(rankFilename.c_str());
      
      TEST_EXIT(!in.fail())("Could not open parallel deserialization file: %s\n",
			    filename.c_str());
440
441
442
443
444

      // Read the revision number of the AMDiS version which was used to create 
      // the serialization file.
      revNumber = -1;
      SerUtil::deserialize(in, revNumber);
445
446
447
448
449
      
      deserialize(in);
      in.close();
      MSG("Deserializtion of mesh distributor from file: %s\n", rankFilename.c_str());
      deserialized = true;
450
451
    }

452
    problemStat.push_back(probStat);
453

454
455
456
    // If the mesh distributor is already initialized, don't forget to set rank
    // DOFs object to the matrices and vectors of the added stationary problem,
    // and to remove the periodic boundary conditions on these objects.
457

458
    if (initialized) {
459
      setRankDofs(probStat);
460
461
      removePeriodicBoundaryConditions(probStat);
    }
462
463
464
  }


465
466
467
468
469
470
471
472
473
474
475
  void MeshDistributor::addProblemStatGlobal(ProblemStatSeq *probStat)
  {
    FUNCNAME("MeshDistributor::addProblemStatGlobal()");

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

    globalMeshDistributor->addProblemStat(probStat);
  }


476
  void MeshDistributor::exitParallelization()
477
  {}
478

479
  
480
  void MeshDistributor::testForMacroMesh()
481
  {
482
    FUNCNAME("MeshDistributor::testForMacroMesh()");
483
484
485
486
487
488
489

    int nMacroElements = 0;

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

      TEST_EXIT(elInfo->getType() == 0)
	("Only macro elements with level 0 are supported!\n");
494
495
496
497
498
499
500
501
502
503
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

504

Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
505
  void MeshDistributor::synchVector(SystemVector &vec, int level)
Thomas Witkowski's avatar
Thomas Witkowski committed
506
  {
507
508
    FUNCNAME("MeshDistributor::synchVector()");

Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
509
    TEST_EXIT_DBG(level >= 0 && level <= 1)("Wrong level number!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
510

511
512
    MSG("-----------------\n");

Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
513
514
515
516
517
518
    MPI::Intracomm &levelComm = levelData.getMpiComm(level);
    DofComm &dc = (level == 0 ? dofComm : dofCommSd);

    StdMpi<vector<double> > stdMpi(levelComm);

    for (DofComm::Iterator it(dc.getSendDofs()); 
519
	 !it.end(); it.nextRank()) {
520
      vector<double> dofs;
521

522
523
      for (int i = 0; i < vec.getSize(); i++) {
	DOFVector<double> &dofVec = *(vec.getDOFVector(i));
524

525
526
	for (it.beginDofIter(vec.getFeSpace(i)); !it.endDofIter(); it.nextDof()) {
	  //	  MSG("SEND TO RANK %d FOR COMP %d\n", it.getRank(), i);
527
	  dofs.push_back(dofVec[it.getDofIndex()]);
528
	}
529
      }
530

Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
531
532
533
534
      int rank = it.getRank();
      if (level > 0)
	rank = levelData.mapRank(rank, 0, level);
      stdMpi.send(rank, dofs);
535
536

      MSG("SEND TO RANK %d OF SIZE %d\n", rank, dofs.size());
537
    }
538
	   
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
539
540
541
542
543
544
    for (DofComm::Iterator it(dc.getRecvDofs()); !it.end(); it.nextRank()) {
      int rank = it.getRank();
      if (level > 0)
	rank = levelData.mapRank(rank, 0, level);
      stdMpi.recv(rank);
    }
545

546
    stdMpi.startCommunication();
547
548
549
550

    for (DofComm::Iterator it(dc.getRecvDofs()); !it.end(); it.nextRank()) {
      MSG("RECV FROM RANK %d OF SIZE %d\n", it.getRank(), stdMpi.getRecvData(it.getRank()).size());
    }
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
551
552
553
554
555
    
    for (DofComm::Iterator it(dc.getRecvDofs()); !it.end(); it.nextRank()) {
      int rank = it.getRank();
      if (level > 0)
	rank = levelData.mapRank(rank, 0, level);
556
557

      int counter = 0;
558
      vector<double> &recvData =  stdMpi.getRecvData(rank);
559
560
561
562

      for (int i = 0; i < vec.getSize(); i++) {
	DOFVector<double> &dofVec = *(vec.getDOFVector(i));

563
564
565
566
567
	for (it.beginDofIter(vec.getFeSpace(i)); !it.endDofIter(); it.nextDof()) {
	  TEST_EXIT_DBG(counter < recvData.size())
	    ("Recv data from rank %d has only %d entries!\n", rank, recvData.size());
	  dofVec[it.getDofIndex()] = recvData[counter++];
	}
568
569
570
571
      }
    }
  }

572

573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
  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);
588
	allEdges.insert(elObjDb.getEdgeLocalMap(elData));
589
590
591
592
593
594
595
      }

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

      elInfo = stack.traverseNext(elInfo);
    }

596
597

    FixRefinementPatch::connectedEdges.clear();
598
    bool valid3dMesh = true;
599
600

    for (std::set<DofEdge>::iterator it = allEdges.begin(); it != allEdges.end(); ++it) {
601
      vector<ElementObjectData>& edgeEls = elObjDb.getElements(*it);
602
603
604
605
606

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

      std::set<int> el0, el1;
607
      map<int, int> edgeNoInEl;
608
609
610

      for (unsigned int i = 0; i < edgeEls.size(); i++) {
	if (rankMacroEls.count(edgeEls[i].elIndex)) {
611
612
613
614
	  if (el0.empty())
	    el0.insert(edgeEls[i].elIndex);
	  else
	    el1.insert(edgeEls[i].elIndex);
615
616
617
618

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

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

649
650
651
	for (std::set<int>::iterator elIt0 = el0.begin(); elIt0 != el0.end(); ++elIt0) {
	  for (std::set<int>::iterator elIt1 = el1.begin(); elIt1 != el1.end(); ++elIt1) {
	    pair<Element*, int> edge0 = 
652
	      make_pair(elObjDb.getElementPtr(*elIt0), edgeNoInEl[*elIt0]);
653
	    pair<Element*, int> edge1 = 
654
	      make_pair(elObjDb.getElementPtr(*elIt1), edgeNoInEl[*elIt1]);
655
656
657
658
659

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

	    WorldVector<double> c0, c1;
660
661
	    mesh->getDofIndexCoords(dofEdge0.first, feSpaces[0], c0);
	    mesh->getDofIndexCoords(dofEdge0.second, feSpaces[0], c1);
662

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
677

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

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


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

    DofContainerSet dofSet;
690
691
    for (DofComm::Iterator it(dofComm.getSendDofs(), level, feSpace); 
	 !it.end(); it.nextRank())
692
      dofSet.insert(it.getDofs().begin(), it.getDofs().end());
693
694
    for (DofComm::Iterator it(dofComm.getRecvDofs(), level, feSpace); 
	 !it.end(); it.nextRank())
695
      dofSet.insert(it.getDofs().begin(), it.getDofs().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
	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");

Thomas Witkowski's avatar
Thomas Witkowski committed
716
	  probStat->getSystemMatrix(i, j)->setDofMap(dofMap[rowFeSpace]);
717
718
	}
    
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
      const FiniteElemSpace *feSpace = probStat->getRhsVector(i)->getFeSpace();
      TEST_EXIT(find(feSpaces.begin(), feSpaces.end(), feSpace) != feSpaces.end())
	("Should not happen!\n");

Thomas Witkowski's avatar
Thomas Witkowski committed
731
732
      probStat->getRhsVector(i)->setDofMap(dofMap[feSpace]);
      probStat->getSolution(i)->setDofMap(dofMap[feSpace]);
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++)
      removePeriodicBoundaryConditions(problemStat[i]);
751
752
753
754
755
756
757
758

    // 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);
    }    
759
760
761

    // Remove periodic vertex associations
    mesh->getPeriodicAssociations().clear();
762
763
764
  }


765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
  void MeshDistributor::removePeriodicBoundaryConditions(ProblemStatSeq *probStat)
  {
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

    int nComponents = probStat->getNumComponents();

    for (int j = 0; j < nComponents; j++) {
      for (int k = 0; k < nComponents; k++) {
	DOFMatrix* mat = probStat->getSystemMatrix(j, k);
	if (mat && mat->getBoundaryManager())
	  removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(mat->getBoundaryManager()->getBoundaryConditionMap()));
      }
      
      if (probStat->getSolution()->getDOFVector(j)->getBoundaryManager())
	removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(probStat->getSolution()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
      
      if (probStat->getRhs()->getDOFVector(j)->getBoundaryManager())
	removePeriodicBoundaryConditions(const_cast<BoundaryIndexMap&>(probStat->getRhs()->getDOFVector(j)->getBoundaryManager()->getBoundaryConditionMap()));
    }
  }


787
  void MeshDistributor::removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap)
Thomas Witkowski's avatar
Thomas Witkowski committed
788
  {
789
790
    FUNCNAME("MeshDistributor::removePeriodicBoundaryConditions()");

Thomas Witkowski's avatar
Thomas Witkowski committed
791
792
    BoundaryIndexMap::iterator it = boundaryMap.begin();
    while (it != boundaryMap.end()) {
793
      if (it->second->isPeriodic())
Thomas Witkowski's avatar
Thomas Witkowski committed
794
	boundaryMap.erase(it++);
795
      else
Thomas Witkowski's avatar
Thomas Witkowski committed
796
797
798
799
800
	++it;      
    }    
  }


801
802
803
804
  void MeshDistributor::createMeshLevelStructure()
  {
    FUNCNAME("MeshDistributor::createMeshLevelStructure()");

805
806
807
    if (mpiSize != 16)
      return;

808
    std::set<int> neighbours;
809
810
    switch (mpiRank) {
    case 0:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
811
      neighbours.insert(1); neighbours.insert(2); neighbours.insert(3);
812
813
      break;
    case 1:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
814
      neighbours.insert(0); neighbours.insert(4); neighbours.insert(2); neighbours.insert(3); neighbours.insert(6);
815
816
      break;
    case 2:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
817
      neighbours.insert(0); neighbours.insert(1); neighbours.insert(3); neighbours.insert(8); neighbours.insert(9);
818
819
      break;
    case 3:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
820
821
822
      neighbours.insert(0); neighbours.insert(1); neighbours.insert(4); 
      neighbours.insert(2); neighbours.insert(6);
      neighbours.insert(8); neighbours.insert(9); neighbours.insert(12); 
823
824
      break;
    case 4:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
825
      neighbours.insert(1); neighbours.insert(3); neighbours.insert(6); neighbours.insert(7); neighbours.insert(5);
826
827
      break;
    case 5:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
828
      neighbours.insert(4); neighbours.insert(6); neighbours.insert(7);
829
830
      break;
    case 6:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
831
832
833
      neighbours.insert(1); neighbours.insert(4); neighbours.insert(5); 
      neighbours.insert(3); neighbours.insert(7);
      neighbours.insert(9); neighbours.insert(12); neighbours.insert(13); 
834
835
      break;
    case 7:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
836
      neighbours.insert(4); neighbours.insert(5); neighbours.insert(6);  neighbours.insert(12); neighbours.insert(13);
837
838
      break;
    case 8:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
839
      neighbours.insert(2); neighbours.insert(3); neighbours.insert(9);  neighbours.insert(10); neighbours.insert(11);
840
841
      break;
    case 9:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
842
843
844
      neighbours.insert(2); neighbours.insert(3); neighbours.insert(6); 
      neighbours.insert(8); neighbours.insert(12);
      neighbours.insert(10); neighbours.insert(11); neighbours.insert(14); 
845
846
      break;
    case 10:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
847
      neighbours.insert(8); neighbours.insert(9); neighbours.insert(11);
848
849
      break;
    case 11:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
850
      neighbours.insert(8); neighbours.insert(9); neighbours.insert(12);  neighbours.insert(10); neighbours.insert(14);
851
852
      break;
    case 12:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
853
854
855
      neighbours.insert(3); neighbours.insert(6); neighbours.insert(7); 
      neighbours.insert(9); neighbours.insert(13);
      neighbours.insert(11); neighbours.insert(14); neighbours.insert(15); 
856
857
      break;
    case 13:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
858
      neighbours.insert(6); neighbours.insert(7); neighbours.insert(12);  neighbours.insert(14); neighbours.insert(15);
859
860
      break;
    case 14:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
861
      neighbours.insert(9); neighbours.insert(12); neighbours.insert(13);  neighbours.insert(11); neighbours.insert(15);
862
863
      break;
    case 15:
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
864
      neighbours.insert(12); neighbours.insert(13); neighbours.insert(14);
865
866
      break;
    }    
867

868
    TEST_EXIT(neighbours.size() > 0)("Should not happen!\n");
869
870
871

    levelData.init(neighbours);

872
873
    MSG("INIT MESH LEVEL %d\n", levelData.getLevelNumber());

874
875
876
877
    bool multiLevelTest = false;
    Parameters::get("parallel->multi level test", multiLevelTest);
    if (multiLevelTest) {
      switch (mpiRank) {
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
878
      case 0: case 1: case 2: case 3:
879
880
	{
	  std::set<int> m;
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
881
	  m.insert(0); m.insert(1); m.insert(2); m.insert(3);
882
	  levelData.addLevel(m, 0);
883
884
	}
	break;
Thomas Witkowski's avatar
Blub    
Thomas Witkowski committed
885
      case 4: case 5: case 6: case 7:
886
887
	{
	  std::set<int> m;