ParallelDomainBase.cc 70.3 KB
Newer Older
Thomas Witkowski's avatar
Thomas Witkowski committed
1
2
#include <algorithm>

3
#include "ParallelDomainBase.h"
4
5
6
7
8
9
10
#include "ParMetisPartitioner.h"
#include "Mesh.h"
#include "Traverse.h"
#include "ElInfo.h"
#include "Element.h"
#include "MacroElement.h"
#include "PartitionElementData.h"
11
12
#include "DOFMatrix.h"
#include "DOFVector.h"
13
#include "SystemVector.h"
14
#include "VtkWriter.h"
15
#include "ElementDofIterator.h"
16
17
#include "ProblemStatBase.h"
#include "StandardProblemIteration.h"
18
#include "ElementFileWriter.h"
19
#include "VertexVector.h"
20
21

#include "petscksp.h"
22
23
24

namespace AMDiS {

25
  PetscErrorCode myKSPMonitor(KSP ksp, PetscInt iter, PetscReal rnorm, void *)
26
  {    
27
    if (iter % 100 == 0 && MPI::COMM_WORLD.Get_rank() == 0)
Thomas Witkowski's avatar
Thomas Witkowski committed
28
      std::cout << "  Petsc-Iteration " << iter << ": " << rnorm << std::endl;
29
30
31
32

    return 0;
  }

33
34
35
36
37
  inline bool cmpDofsByValue(const DegreeOfFreedom* dof1, const DegreeOfFreedom* dof2)
  {
    return (*dof1 < *dof2);
  }

38
  ParallelDomainBase::ParallelDomainBase(ProblemIterationInterface *iIF,
39
40
41
					 ProblemTimeInterface *tIF,
					 FiniteElemSpace *fe,
					 RefinementManager *refineManager)
42
43
    : iterationIF(iIF),
      timeIF(tIF),
44
      name(iIF->getName()),
45
46
      feSpace(fe),
      mesh(fe->getMesh()),
47
      refinementManager(refineManager),
48
      initialPartitionMesh(true),
49
      nRankDofs(0),
50
      rstart(0),
51
52
      nComponents(1),
      deserialized(false)
53
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
54
55
56
57
58
59
60
    FUNCNAME("ParallelDomainBase::ParalleDomainBase()");

    TEST_EXIT(mesh->getNumberOfDOFAdmin() == 1)
      ("Only meshes with one DOFAdmin are supported!\n");
    TEST_EXIT(mesh->getDOFAdmin(0).getNumberOfPreDOFs(0) == 0)
      ("Wrong pre dof number for DOFAdmin!\n");

61
62
63
64
65
66
    mpiRank = MPI::COMM_WORLD.Get_rank();
    mpiSize = MPI::COMM_WORLD.Get_size();
    mpiComm = MPI::COMM_WORLD;
    partitioner = new ParMetisPartitioner(mesh, &mpiComm);
  }

67
  void ParallelDomainBase::initParallelization(AdaptInfo *adaptInfo)
68
  {
69
70
71
72
73
74
75
    FUNCNAME("ParallelDomainBase::initParallelization()");

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

    // If the problem has been already read from a file, we do not need to do anything.
    if (deserialized)
76
77
      return;

78
79
80
81
82
    // 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();

83
84
85
86
87
88
89
    // create an initial partitioning of the mesh
    partitioner->createPartitionData();
    // set the element weights, which are 1 at the very first begin
    setElemWeights(adaptInfo);
    // and now partition the mesh
    partitionMesh(adaptInfo);   

Thomas Witkowski's avatar
Thomas Witkowski committed
90
91
92
#if (DEBUG != 0)
    ElementIdxToDofs elMap;
    DbgCreateElementMap(elMap);
93
94
95

    if (mpiRank == 0)
      writePartitioningMesh("part.vtu");
Thomas Witkowski's avatar
Thomas Witkowski committed
96
#endif
97

98
    // === Create new global and local DOF numbering. ===
99

100
    // Set of all DOFs of the rank.
101
    std::vector<const DegreeOfFreedom*> rankDofs;
102
    // Number of DOFs in ranks partition that are owned by the rank.
103
    nRankDofs = 0;
104
    // Number of all DOFs in the macro mesh.
105
    int nOverallDOFs = 0;
106

107
    createLocalGlobalNumbering(rankDofs, nRankDofs, nOverallDOFs);
108

Thomas Witkowski's avatar
Thomas Witkowski committed
109
110
    // === Create interior boundary information ===

111
    createInteriorBoundaryInfo(rankDofs);
Thomas Witkowski's avatar
Thomas Witkowski committed
112

Thomas Witkowski's avatar
n    
Thomas Witkowski committed
113
114
115
116
    // === Remove all macro elements that are not part of the rank partition. ===

    removeMacroElements();

Thomas Witkowski's avatar
Thomas Witkowski committed
117
#if (DEBUG != 0)
Thomas Witkowski's avatar
Thomas Witkowski committed
118
    DbgTestElementMap(elMap);
Thomas Witkowski's avatar
Thomas Witkowski committed
119
120
    DbgTestInteriorBoundary();
#endif
Thomas Witkowski's avatar
Thomas Witkowski committed
121

122
    // === Reset all DOFAdmins of the mesh. ===
123

124
    updateDofAdmins();
125

126
127
    // === ===

128
    //    createPeriodicMap();
129

130
    // === Global refinements. ===
Thomas Witkowski's avatar
Thomas Witkowski committed
131

Thomas Witkowski's avatar
Thomas Witkowski committed
132
133
134
    int globalRefinement = 0;
    GET_PARAMETER(0, "testgr", "%d", &globalRefinement);

Thomas Witkowski's avatar
Thomas Witkowski committed
135
136
    if (globalRefinement > 0) {
      refinementManager->globalRefine(mesh, globalRefinement);
137

138
139
140
141
142
#if (DEBUG != 0)
      elMap.clear();
      DbgCreateElementMap(elMap);
#endif

143
      updateLocalGlobalNumbering(nRankDofs, nOverallDOFs);
144
145
146
147
148
149

      updateDofAdmins();

#if (DEBUG != 0)
      DbgTestElementMap(elMap);
#endif
150
151

      createPeriodicMap();
Thomas Witkowski's avatar
Thomas Witkowski committed
152
153
    }

154

Thomas Witkowski's avatar
Thomas Witkowski committed
155
#if (DEBUG != 0)
156
    //    DbgTestCommonDofs(true);
Thomas Witkowski's avatar
Thomas Witkowski committed
157
#endif
158

159
    nRankRows = nRankDofs * nComponents;
160
    nOverallRows = nOverallDOFs * nComponents;
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

#if 0
    DOFVector<double> *tmp = new DOFVector<double>(feSpace, "tmp");
    tmp->set(0.0);
    if (mpiRank == 0)
      VtkWriter::writeFile(tmp, "test0.vtu");
    else
      VtkWriter::writeFile(tmp, "test1.vtu");

    if (mpiRank == 1) {
      for (PeriodicDofMap::iterator it = periodicDof.begin();
	   it != periodicDof.end(); ++it) {
	std::cout << "DOF MAP " << it->first << ": ";
	for (std::set<DegreeOfFreedom>::iterator dofit = it->second.begin();
	     dofit != it->second.end(); ++dofit)
	  std::cout << *dofit << " ";
	std::cout << std::endl;

	DegreeOfFreedom localdof;
	for (DofMapping::iterator dofIt = mapLocalGlobalDOFs.begin();
	     dofIt != mapLocalGlobalDOFs.end(); ++dofIt)
	  if (dofIt->second == it->first)
	    localdof = dofIt->first;

	WorldVector<double> coords;
	mesh->getDofIndexCoords(localdof, feSpace, coords);
	coords.print();
      }
    }
#endif

    if (mpiRank == 0)
      writePartitioningMesh("part.vtu");
194
195
  }

196
197

  void ParallelDomainBase::exitParallelization(AdaptInfo *adaptInfo)
198
  {}
199

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
  
  void ParallelDomainBase::updateDofAdmins()
  {
    int nAdmins = mesh->getNumberOfDOFAdmin();
    for (int i = 0; i < nAdmins; i++) {
      DOFAdmin& admin = const_cast<DOFAdmin&>(mesh->getDOFAdmin(i));
      
      for (int j = 0; j < admin.getSize(); j++)
	admin.setDOFFree(j, true);
      for (int j = 0; j < static_cast<int>(mapLocalGlobalDOFs.size()); j++)
 	admin.setDOFFree(j, false);

      admin.setUsedSize(mapLocalGlobalDOFs.size());
      admin.setUsedCount(mapLocalGlobalDOFs.size());
      admin.setFirstHole(mapLocalGlobalDOFs.size());
    }
  }

218

219
220
221
222
223
224
225
226
227
228
  void ParallelDomainBase::testForMacroMesh()
  {
    FUNCNAME("ParallelDomainBase::testForMacroMesh()");

    int nMacroElements = 0;

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1, Mesh::CALL_LEAF_EL);
    while (elInfo) {
      TEST_EXIT(elInfo->getLevel() == 0)
229
	("Mesh is already refined! This does not work with parallelization!\n");
230
231
232
233
234
235
236
237
238
239
      
      nMacroElements++;

      elInfo = stack.traverseNext(elInfo);
    }

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

240
241
  void ParallelDomainBase::setDofMatrix(DOFMatrix* mat, int dispMult, 
					int dispAddRow, int dispAddCol)
242
  {
243
244
245
246
    FUNCNAME("ParallelDomainBase::setDofMatrix()");

    TEST_EXIT(mat)("No DOFMatrix!\n");

247
    using mtl::tag::row; using mtl::tag::nz; using mtl::begin; using mtl::end;
248
249
250
251
252
253
    namespace traits= mtl::traits;
    typedef DOFMatrix::base_matrix_type Matrix;

    traits::col<Matrix>::type col(mat->getBaseMatrix());
    traits::const_value<Matrix>::type value(mat->getBaseMatrix());

254
    typedef traits::range_generator<row, Matrix>::type cursor_type;
255
256
    typedef traits::range_generator<nz, cursor_type>::type icursor_type;

257
258
259
260
261
262
263
264
265
266
267
    std::vector<int> cols;
    std::vector<double> values;
    cols.reserve(300);
    values.reserve(300);

    for (cursor_type cursor = begin<row>(mat->getBaseMatrix()), 
	   cend = end<row>(mat->getBaseMatrix()); cursor != cend; ++cursor) {

      cols.clear();
      values.clear();

268
269
      int globalRowDof = mapLocalGlobalDOFs[*cursor];
      bool periodicRow = (periodicDof.count(globalRowDof) > 0);
270

271
272
      for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor); 
	   icursor != icend; ++icursor) {
273
	if (value(*icursor) != 0.0) {
274
275
276
	  int globalColDof = mapLocalGlobalDOFs[col(*icursor)];
	  int colIndex = globalColDof * dispMult + dispAddCol;

277
278
279
 	  if (periodicRow == false && periodicDof.count(globalColDof) > 0) {
 	    cols.push_back(colIndex);
 	    values.push_back(value(*icursor) * 0.5);
280

281
282
283
284
285
286
 	    for (std::set<DegreeOfFreedom>::iterator it = periodicDof[globalColDof].begin();
 		 it != periodicDof[globalColDof].end(); ++it) {
 	      cols.push_back(*it * dispMult + dispAddCol);
 	      values.push_back(value(*icursor) * 0.5);
 	    }
 	  } else {
287
288
289
	    cols.push_back(colIndex);
	    values.push_back(value(*icursor));
	  }
290
	}
291
292
293
      }

      int rowIndex = globalRowDof * dispMult + dispAddRow;
294
      
295
296
      if (periodicRow) {
	int diagIndex = -1;
297
	
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
	for (int i = 0; i < static_cast<int>(values.size()); i++) {
	  if (cols[i] != rowIndex)
	    values[i] *= 0.5;
	  else
	    diagIndex = i;
	}

	MatSetValues(petscMatrix, 1, &rowIndex, cols.size(), &(cols[0]), &(values[0]), ADD_VALUES);	

	if (diagIndex != -1)
	  values[diagIndex] = 0.0;

	for (std::set<DegreeOfFreedom>::iterator it = periodicDof[globalRowDof].begin();
	     it != periodicDof[globalRowDof].end(); ++it) {
	  int perRowIndex = *it * dispMult + dispAddRow;
	  MatSetValues(petscMatrix, 1, &perRowIndex, cols.size(), &(cols[0]), &(values[0]), ADD_VALUES);
	}

      } else {
	MatSetValues(petscMatrix, 1, &rowIndex, cols.size(), &(cols[0]), &(values[0]), ADD_VALUES);
318
      }    
319
    }
320
  }
321

322

323
  void ParallelDomainBase::setDofVector(Vec& petscVec, DOFVector<double>* vec, 
324
325
					int dispMult, int dispAdd)
  {
326
327
    DOFVector<double>::Iterator dofIt(vec, USED_DOFS);
    for (dofIt.reset(); !dofIt.end(); ++dofIt) {
328
329
330
331
332
333
334
335
336
337
338
339
      int globalRow = mapLocalGlobalDOFs[dofIt.getDOFIndex()];
      int index = globalRow * dispMult + dispAdd;

      if (periodicDof.count(globalRow) > 0) {
	double value = *dofIt * 0.5;
	VecSetValues(petscVec, 1, &index, &value, ADD_VALUES);

	for (std::set<DegreeOfFreedom>::iterator it = periodicDof[globalRow].begin();
	     it != periodicDof[globalRow].end(); ++it) {
	  index = *it * dispMult + dispAdd;
	  VecSetValues(petscVec, 1, &index, &value, ADD_VALUES);
	}
340

341
342
343
344
      } else {
	double value = *dofIt;
	VecSetValues(petscVec, 1, &index, &value, ADD_VALUES);
      }
345
    }    
346
347
  }

348

349
350
  void ParallelDomainBase::fillPetscMatrix(DOFMatrix *mat, DOFVector<double> *vec)
  {
351
352
353
354
    MatCreate(PETSC_COMM_WORLD, &petscMatrix);
    MatSetSizes(petscMatrix, nRankRows, nRankRows, nOverallRows, nOverallRows);
    MatSetType(petscMatrix, MATAIJ);

355
356
357
358
359
360
361
362
363
364
365
366
    VecCreate(PETSC_COMM_WORLD, &petscRhsVec);
    VecSetSizes(petscRhsVec, nRankRows, nOverallRows);
    VecSetType(petscRhsVec, VECMPI);

    VecCreate(PETSC_COMM_WORLD, &petscSolVec);
    VecSetSizes(petscSolVec, nRankRows, nOverallRows);
    VecSetType(petscSolVec, VECMPI);

    VecCreate(PETSC_COMM_WORLD, &petscTmpVec);
    VecSetSizes(petscTmpVec, nRankRows, nOverallRows);
    VecSetType(petscTmpVec, VECMPI);

367
368
369
370
371
    setDofMatrix(mat);

    MatAssemblyBegin(petscMatrix, MAT_FINAL_ASSEMBLY);
    MatAssemblyEnd(petscMatrix, MAT_FINAL_ASSEMBLY);

372
    setDofVector(petscRhsVec, vec);
Thomas Witkowski's avatar
Thomas Witkowski committed
373
374
375

    VecAssemblyBegin(petscRhsVec);
    VecAssemblyEnd(petscRhsVec);
376
377
378
379
380
  }

  
  void ParallelDomainBase::fillPetscMatrix(Matrix<DOFMatrix*> *mat, SystemVector *vec)
  {
381
382
383
384
    FUNCNAME("ParallelDomainBase::fillPetscMatrix()");

    clock_t first = clock();

385
386
387
388
389
390
391
392
393
394
395
396
    VecCreate(PETSC_COMM_WORLD, &petscRhsVec);
    VecSetSizes(petscRhsVec, nRankRows, nOverallRows);
    VecSetType(petscRhsVec, VECMPI);

    VecCreate(PETSC_COMM_WORLD, &petscSolVec);
    VecSetSizes(petscSolVec, nRankRows, nOverallRows);
    VecSetType(petscSolVec, VECMPI);

    VecCreate(PETSC_COMM_WORLD, &petscTmpVec);
    VecSetSizes(petscTmpVec, nRankRows, nOverallRows);
    VecSetType(petscTmpVec, VECMPI);

397
    using mtl::tag::row; using mtl::tag::nz; using mtl::begin; using mtl::end;
398
399
400
401
    namespace traits= mtl::traits;
    typedef DOFMatrix::base_matrix_type Matrix;

    int d_nnz[nRankRows];
402
403
    int o_nnz[nRankRows];

404
405
    std::map<int, std::vector< std::pair<int, int> > > sendMatrixEntry;

406
    for (int i = 0; i < nRankRows; i++) {
407
      d_nnz[i] = 0;
408
409
      o_nnz[i] = 0;
    }
410

411
412
    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++) {
413
414
415
416
417
418
 	if ((*mat)[i][j]) {
	  Matrix bmat = (*mat)[i][j]->getBaseMatrix();

	  traits::col<Matrix>::type col(bmat);
	  traits::const_value<Matrix>::type value(bmat);
	  
419
	  typedef traits::range_generator<row, Matrix>::type cursor_type;
420
421
	  typedef traits::range_generator<nz, cursor_type>::type icursor_type;
	  
422
423
424
425
426
	  for (cursor_type cursor = begin<row>(bmat), 
		 cend = end<row>(bmat); cursor != cend; ++cursor) {

	    int r = mapLocalGlobalDOFs[*cursor] * nComponents + i;

427
428
	    if (isRankDof[*cursor]) {
	      r -= rstart * nComponents;
429
430
431
432
433
434
435
436
437
438

#if (DEBUG != 0)    
	      if (r < 0 || r >= nRankRows) {
		std::cout << "ERROR in rank: " << mpiRank << std::endl;
		std::cout << "  Wrong r = " << r << " " << *cursor << " " 
			  << mapLocalGlobalDOFs[*cursor] << " " 
			  << nRankRows << std::endl;
		ERROR_EXIT("Should not happen!\n");
	      }
#endif
439
	      
440
441
442
443
	      for (icursor_type icursor = begin<nz>(cursor), 
		     icend = end<nz>(cursor); icursor != icend; ++icursor) {
		if (value(*icursor) != 0.0) {
		  int c = mapLocalGlobalDOFs[col(*icursor)] * nComponents + j;
444

445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
		  if (c >= rstart * nComponents && 
		      c < rstart * nComponents + nRankRows)
		    d_nnz[r]++;
		  else
		    o_nnz[r]++;		  
		}    
	      }
	    } else {
	      int sendToRank = -1;

	      for (RankToDofContainer::iterator it = recvDofs.begin();
		   it != recvDofs.end(); ++it) {
		for (DofContainer::iterator dofIt = it->second.begin();
		     dofIt != it->second.end(); ++dofIt) {
		  if (**dofIt == *cursor) {
		    sendToRank = it->first;
		    break;
		  }
		}

		if (sendToRank != -1)
		  break;
	      }

	      TEST_EXIT_DBG(sendToRank != -1)("Should not happen!\n");

	      for (icursor_type icursor = begin<nz>(cursor), 
		     icend = end<nz>(cursor); icursor != icend; ++icursor) {
		if (value(*icursor) != 0.0) {
		  int c = mapLocalGlobalDOFs[col(*icursor)] * nComponents + j;
		  
		  sendMatrixEntry[sendToRank].push_back(std::make_pair(r, c));
		}
	      }
	    }
480
481
	  }
	}
482
483
484
485
486
487
488
489
490
491
492
493
      }
    }

    MPI::Request request[sendDofs.size() + recvDofs.size()];
    int requestCounter = 0;

    std::vector<int*> sendBuffers;
    sendBuffers.reserve(recvDofs.size());

    for (RankToDofContainer::iterator it = recvDofs.begin(); 
	 it != recvDofs.end(); ++it) {
      int nSend = sendMatrixEntry[it->first].size();
494

495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
      request[requestCounter++] = mpiComm.Isend(&nSend, 1, MPI_INT, it->first, 0);
      
      if (nSend > 0) {
	int *sendbuf = new int[nSend * 2];
	for (int i = 0; i < nSend; i++) {
	  sendbuf[i * 2] = sendMatrixEntry[it->first][i].first;
	  sendbuf[i * 2 + 1] = sendMatrixEntry[it->first][i].second;
	}
	sendBuffers.push_back(sendbuf);
      } else {
	sendBuffers.push_back(NULL);
      }
    }

    std::vector<int> recvSize;
    recvSize.reserve(sendDofs.size());
    
    int i = 0;
    for (RankToDofContainer::iterator it = sendDofs.begin();
	 it != sendDofs.end(); ++it)
      request[requestCounter++] = 
	mpiComm.Irecv(&(recvSize[i++]), 1, MPI_INT, it->first, 0);

    MPI::Request::Waitall(requestCounter, request);

    requestCounter = 0;

    i = 0;
    for (RankToDofContainer::iterator it = recvDofs.begin(); 
	 it != recvDofs.end(); ++it) {
      int nSend = sendMatrixEntry[it->first].size();

527
      if (nSend > 0)
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
	request[requestCounter++] = 
	  mpiComm.Isend(sendBuffers[i], nSend * 2, MPI_INT, it->first, 0);

      i++;
    }

    std::vector<int*> recvBuffers;
    recvBuffers.reserve(sendDofs.size());
    
    i = 0;
    for (RankToDofContainer::iterator it = sendDofs.begin();
	 it != sendDofs.end(); ++it) {
      if (recvSize[i] > 0) {
	int *recvbuf = new int[recvSize[i] * 2];
	recvBuffers.push_back(recvbuf);

	request[requestCounter++] =
	  mpiComm.Irecv(recvbuf, recvSize[i] * 2, MPI_INT, it->first, 0);
      } else {
	recvBuffers.push_back(NULL);
      }

      i++;
    }

    MPI::Request::Waitall(requestCounter, request);
Thomas Witkowski's avatar
Thomas Witkowski committed
554

555
556
    for (int j = 0; j < static_cast<int>(sendBuffers.size()); j++)
      if (sendBuffers[j])
Thomas Witkowski's avatar
Thomas Witkowski committed
557
 	delete [] sendBuffers[j];
558
559
560
561
562
563
564
565

    i = 0;
    for (RankToDofContainer::iterator it = sendDofs.begin();
	 it != sendDofs.end(); ++it) {
      if (recvSize[i] > 0) {
	for (int j = 0; j < recvSize[i]; j++) {
	  int r = recvBuffers[i][j * 2];
	  int c = recvBuffers[i][j * 2 + 1];
566

567
	  r -= rstart * nComponents;
Thomas Witkowski's avatar
Thomas Witkowski committed
568

569
570
	  TEST_EXIT_DBG(r >= 0 && r < nRankRows)("Should not happen!\n");
	  
571
	  if (c < rstart * nComponents || c >= rstart * nComponents + nRankRows)
572
	    o_nnz[r]++;
573
574
	  else
	    d_nnz[r]++;
575
576
577
578
	}

	delete [] recvBuffers[i];
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
579
580

      i++;
581
    }
582
583

    MatCreateMPIAIJ(PETSC_COMM_WORLD, nRankRows, nRankRows, nOverallRows, nOverallRows,
584
585
586
587
588
589
590
591
		    0, d_nnz, 0, o_nnz, &petscMatrix);

#if (DEBUG != 0)
    int a, b;
    MatGetOwnershipRange(petscMatrix, &a, &b);
    TEST_EXIT(a == rstart * nComponents)("Wrong matrix ownership range!\n");
    TEST_EXIT(b == rstart * nComponents + nRankRows)("Wrong matrix ownership range!\n");
#endif
592

593
594
595
596
597
598
    using mtl::tag::major; using mtl::tag::nz; using mtl::begin; using mtl::end;
    namespace traits= mtl::traits;
    typedef DOFMatrix::base_matrix_type Matrix;

    for (int i = 0; i < nComponents; i++)
      for (int j = 0; j < nComponents; j++)
599
	if ((*mat)[i][j])
600
601
602
603
604
605
	  setDofMatrix((*mat)[i][j], nComponents, i, j);

    MatAssemblyBegin(petscMatrix, MAT_FINAL_ASSEMBLY);
    MatAssemblyEnd(petscMatrix, MAT_FINAL_ASSEMBLY);

    for (int i = 0; i < nComponents; i++)
606
      setDofVector(petscRhsVec, vec->getDOFVector(i), nComponents, i);
607

608
609
610
    VecAssemblyBegin(petscRhsVec);
    VecAssemblyEnd(petscRhsVec);

611
    INFO(info, 8)("Fill petsc matrix needed %.5f seconds\n", TIME_USED(first, clock()));
612
613
614
  }


615
  void ParallelDomainBase::solvePetscMatrix(DOFVector<double> *vec)
616
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
617
618
    FUNCNAME("ParallelDomainBase::solvePetscMatrix()");

619
620
621
622
    KSP ksp;
    PC pc;

    KSPCreate(PETSC_COMM_WORLD, &ksp);
623
    KSPSetOperators(ksp, petscMatrix, petscMatrix, SAME_NONZERO_PATTERN);
624
    KSPGetPC(ksp, &pc);
625
626
    //PCSetType(pc, PCJACOBI);
    PCSetType(pc, PCILU);
627
    KSPSetTolerances(ksp, 1.e-7, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT);
628
629
    KSPSetType(ksp, KSPBCGS);
    //KSPSetType(ksp, KSPCG);
630
    KSPMonitorSet(ksp, myKSPMonitor, PETSC_NULL, 0);
631
632
633
634
635
    KSPSolve(ksp, petscRhsVec, petscSolVec);

    PetscScalar *vecPointer;
    VecGetArray(petscSolVec, &vecPointer);

636
    for (int i = 0; i < nRankDofs; i++)
637
      (*vec)[mapLocalToDofIndex[i]] = vecPointer[i];
638
639
640

    VecRestoreArray(petscSolVec, &vecPointer);

641
642
    std::vector<double*> sendBuffers(sendDofs.size());
    std::vector<double*> recvBuffers(recvDofs.size());
Thomas Witkowski's avatar
Thomas Witkowski committed
643
644
645

    MPI::Request request[sendDofs.size() + recvDofs.size()];
    int requestCounter = 0;
646
647
    
    int i = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
648
    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
649
	 sendIt != sendDofs.end(); ++sendIt, i++) {
650
651
      int nSendDOFs = sendIt->second.size();
      sendBuffers[i] = new double[nSendDOFs];
652

653
      for (int j = 0; j < nSendDOFs; j++)
Thomas Witkowski's avatar
Thomas Witkowski committed
654
	sendBuffers[i][j] = (*vec)[*((sendIt->second)[j])];
655

Thomas Witkowski's avatar
Thomas Witkowski committed
656
657
      request[requestCounter++] =
	mpiComm.Isend(sendBuffers[i], nSendDOFs, MPI_DOUBLE, sendIt->first, 0);
658
659
660
    }

    i = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
661
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
662
	 recvIt != recvDofs.end(); ++recvIt, i++) {
663
664
      int nRecvDOFs = recvIt->second.size();
      recvBuffers[i] = new double[nRecvDOFs];
665

Thomas Witkowski's avatar
Thomas Witkowski committed
666
667
      request[requestCounter++] =
	mpiComm.Irecv(recvBuffers[i], nRecvDOFs, MPI_DOUBLE, recvIt->first, 0);
668
669
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
670
671
672

    MPI::Request::Waitall(requestCounter, request);

673
    i = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
674
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
675
	 recvIt != recvDofs.end(); ++recvIt, i++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
676
      for (int j = 0; j < static_cast<int>(recvIt->second.size()); j++)
Thomas Witkowski's avatar
Thomas Witkowski committed
677
	(*vec)[*(recvIt->second)[j]] = recvBuffers[i][j];
678
679
680
681

      delete [] recvBuffers[i];
    }
    
682
    for (int i = 0; i < static_cast<int>(sendBuffers.size()); i++)
683
      delete [] sendBuffers[i];
684
685

    MatDestroy(petscMatrix);
686
687
688
    VecDestroy(petscRhsVec);
    VecDestroy(petscSolVec);
    VecDestroy(petscTmpVec);
689
690
  }

691

692
  void ParallelDomainBase::solvePetscMatrix(SystemVector &vec)
693
694
695
  {
    FUNCNAME("ParallelDomainBase::solvePetscMatrix()");

696
697
698
699
700
701
702
703
704
#if 0
    // Set old solution to be initiual guess for petsc solver.
    for (int i = 0; i < nComponents; i++)
      setDofVector(petscSolVec, vec->getDOFVector(i), nComponents, i);

    VecAssemblyBegin(petscSolVec);
    VecAssemblyEnd(petscSolVec);
#endif

705
    KSP solver;
706

707
708
709
    KSPCreate(PETSC_COMM_WORLD, &solver);
    KSPSetOperators(solver, petscMatrix, petscMatrix, SAME_NONZERO_PATTERN); 

710
711
    KSPSetTolerances(solver, 0.0, 1e-8, PETSC_DEFAULT, PETSC_DEFAULT);

712
713
    KSPSetType(solver, KSPBCGS);
    KSPMonitorSet(solver, myKSPMonitor, PETSC_NULL, 0);
714
    KSPSetFromOptions(solver);
715
716
    // Do not delete the solution vector, use it for the initial guess.
    //    KSPSetInitialGuessNonzero(solver, PETSC_TRUE);
717
718

    KSPSolve(solver, petscRhsVec, petscSolVec);
719
720
721
722
723

    PetscScalar *vecPointer;
    VecGetArray(petscSolVec, &vecPointer);

    for (int i = 0; i < nComponents; i++) {
724
      DOFVector<double> *dofvec = vec.getDOFVector(i);
725
      for (int j = 0; j < nRankDofs; j++)
726
	(*dofvec)[mapLocalToDofIndex[j]] = vecPointer[j * nComponents + i];      
727
728
729
730
    }

    VecRestoreArray(petscSolVec, &vecPointer);

731
    synchVectors(vec);
732

733
734
735
736
737
738
739
740
741
742
743
    int iterations = 0;
    KSPGetIterationNumber(solver, &iterations);
    MSG("  Number of iterations: %d\n", iterations);
    
    double norm = 0.0;
    MatMult(petscMatrix, petscSolVec, petscTmpVec);
    VecAXPY(petscTmpVec, -1.0, petscRhsVec);
    VecNorm(petscTmpVec, NORM_2, &norm);
    MSG("  Residual norm: %e\n", norm);

    MatDestroy(petscMatrix);
744
745
746
    VecDestroy(petscRhsVec);
    VecDestroy(petscSolVec);
    VecDestroy(petscTmpVec);
747
748
749
750
751
    KSPDestroy(solver);
  }
  
  void ParallelDomainBase::synchVectors(SystemVector &vec)
  {
752
753
754
755
756
757
758
759
760
    std::vector<double*> sendBuffers(sendDofs.size());
    std::vector<double*> recvBuffers(recvDofs.size());

    MPI::Request request[sendDofs.size() + recvDofs.size()];
    int requestCounter = 0;
    
    int i = 0;
    for (RankToDofContainer::iterator sendIt = sendDofs.begin();
	 sendIt != sendDofs.end(); ++sendIt, i++) {
761
762
      int nSendDOFs = sendIt->second.size();
      sendBuffers[i] = new double[nSendDOFs * nComponents];
763
764
765

      int counter = 0;
      for (int j = 0; j < nComponents; j++) {
766
	DOFVector<double> *dofvec = vec.getDOFVector(j);
767
768
769
770
	for (int k = 0; k < nSendDOFs; k++)
	  sendBuffers[i][counter++] = (*dofvec)[*((sendIt->second)[k])];
      }

771
772
      request[requestCounter++] = mpiComm.Isend(sendBuffers[i], nSendDOFs * nComponents,
						MPI_DOUBLE, sendIt->first, 0);
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
    }

    i = 0;
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt, i++) {
      int nRecvDOFs = recvIt->second.size() * nComponents;
      recvBuffers[i] = new double[nRecvDOFs];

      request[requestCounter++] =
	mpiComm.Irecv(recvBuffers[i], nRecvDOFs, MPI_DOUBLE, recvIt->first, 0);
    }


    MPI::Request::Waitall(requestCounter, request);

    i = 0;
    for (RankToDofContainer::iterator recvIt = recvDofs.begin();
	 recvIt != recvDofs.end(); ++recvIt, i++) {
      int nRecvDOFs = recvIt->second.size();

      int counter = 0;
      for (int j = 0; j < nComponents; j++) {
795
	DOFVector<double> *dofvec = vec.getDOFVector(j);
796
797
 	for (int k = 0; k < nRecvDOFs; k++)
 	  (*dofvec)[*(recvIt->second)[k]] = recvBuffers[i][counter++];
798
799
800
801
802
803
804
805
806
      }

      delete [] recvBuffers[i];
    }
    
    for (int i = 0; i < static_cast<int>(sendBuffers.size()); i++)
      delete [] sendBuffers[i];
  }

807
808
809
810
  
  void ParallelDomainBase::serialize(std::ostream &out, DofContainer &data)
  {
    int vecSize = data.size();
811
    SerUtil::serialize(out, vecSize);
812
813
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = (*data[i]);
814
      SerUtil::serialize(out, dofIndex);
815
816
817
818
819
820
821
822
823
824
    }
  }


  void ParallelDomainBase::deserialize(std::istream &in, DofContainer &data,
				       std::map<int, const DegreeOfFreedom*> &dofMap)
  {
    FUNCNAME("ParallelDomainBase::deserialize()");

    int vecSize = 0;
825
    SerUtil::deserialize(in, vecSize);
826
827
828
    data.resize(vecSize);
    for (int i = 0; i < vecSize; i++) {
      int dofIndex = 0;
829
      SerUtil::deserialize(in, dofIndex);
830
831
832
833
834
835
836
837
838
839
840
841

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

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


  void ParallelDomainBase::serialize(std::ostream &out, RankToDofContainer &data)
  {
    int mapSize = data.size();
842
    SerUtil::serialize(out, mapSize);
843
844
    for (RankToDofContainer::iterator it = data.begin(); it != data.end(); ++it) {
      int rank = it->first;
845
      SerUtil::serialize(out, rank);
846
847
848
849
850
851
852
853
854
      serialize(out, it->second);
    }
  }

  
  void ParallelDomainBase::deserialize(std::istream &in, RankToDofContainer &data,
				       std::map<int, const DegreeOfFreedom*> &dofMap)
  {
    int mapSize = 0;
855
    SerUtil::deserialize(in, mapSize);
856
857
    for (int i = 0; i < mapSize; i++) {
      int rank = 0;
858
      SerUtil::deserialize(in, rank);
859
860
861
862
      deserialize(in, data[rank], dofMap);      
    }
  }

863

864
  double ParallelDomainBase::setElemWeights(AdaptInfo *adaptInfo) 
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
  {
    double localWeightSum = 0.0;
    int elNum = -1;

    elemWeights.clear();

    TraverseStack stack;
    ElInfo *elInfo = stack.traverseFirst(mesh, -1,
					 Mesh::CALL_EVERY_EL_PREORDER);
    while (elInfo) {
      Element *element = elInfo->getElement();

      // get partition data
      PartitionElementData *partitionData = dynamic_cast<PartitionElementData*>
	(element->getElementData(PARTITION_ED));

      if (partitionData && partitionData->getPartitionStatus() == IN) {
882
	if (partitionData->getLevel() == 0)
883
	  elNum = element->getIndex();
884
	
Thomas Witkowski's avatar
Thomas Witkowski committed
885
	TEST_EXIT_DBG(elNum != -1)("invalid element number\n");
886
887
888
889
890
891
892
893
894
895
896
897
	if (element->isLeaf()) {
	  elemWeights[elNum] += 1.0;
	  localWeightSum += 1.0;
	}
      }

      elInfo = stack.traverseNext(elInfo);
    }

    return localWeightSum;
  }

898

899
  void ParallelDomainBase::partitionMesh(AdaptInfo *adaptInfo)
900
901
902
903
904
905
906
907
908
909
910
911
912
  {
    if (initialPartitionMesh) {
      initialPartitionMesh = false;
      partitioner->fillCoarsePartitionVec(&oldPartitionVec);
      partitioner->partition(&elemWeights, INITIAL);
    } else {
      oldPartitionVec = partitionVec;
      partitioner->partition(&elemWeights, ADAPTIVE_REPART, 100.0 /*0.000001*/);
    }    

    partitioner->fillCoarsePartitionVec(&partitionVec);
  }

913

914
  void ParallelDomainBase::createInteriorBoundaryInfo(DofContainer& rankDofs)
915
  {
916
    FUNCNAME("ParallelDomainBase::createInteriorBoundaryInfo()");
Thomas Witkowski's avatar
Thomas Witkowski committed
917

918
919
920
921
922
    // To be general, we have to use elInfo->getBoundary(EDGE/FACE, i) instead of
    // elInfo->getBoundar(i).
    TEST_EXIT(mesh->getDim() == 2)
      ("getBoundary(i) returns always i-th edge, generalize for 3d!\n");

Thomas Witkowski's avatar
Thomas Witkowski committed
923
924
    // === First, create all the information about the interior boundaries. ===

925
    TraverseStack stack;
926
927
928
    ElInfo *elInfo = 
      stack.traverseFirst(mesh, -1, 
			  Mesh::CALL_LEAF_EL | Mesh::FILL_NEIGH | Mesh::FILL_BOUND);
929
930
931
932
933
    while (elInfo) {
      Element *element = elInfo->getElement();

      PartitionElementData *partitionData = 
	dynamic_cast<PartitionElementData*>(element->getElementData(PARTITION_ED));   
934

935
936
937
938
939
940
941
      if (partitionData->getPartitionStatus() == IN) {
	for (int i = 0; i < 3; i++) {
	  if (!elInfo->getNeighbour(i))
	    continue;

	  PartitionElementData *neighbourPartitionData =
	    dynamic_cast<PartitionElementData*>(elInfo->getNeighbour(i)->getElementData(PARTITION_ED));
942

943
 	  if (neighbourPartitionData->getPartitionStatus() == OUT) {
Thomas Witkowski's avatar
Thomas Witkowski committed
944

945
	    AtomicBoundary bound;	    	    
946
	    bound.rankObject.el = element;
947
	    bound.rankObject.elIndex = element->getIndex();
948
949
	    bound.rankObject.subObjAtBoundary = EDGE;
	    bound.rankObject.ithObjAtBoundary = i;
950
951
952
953
	    // Do not set a pointer to the element, because if will be deleted from
	    // mesh after partitioning and the pointer would become invalid.
	    bound.neighbourObject.el = NULL;
	    bound.neighbourObject.elIndex = elInfo->getNeighbour(i)->getIndex();
954
	    bound.neighbourObject.subObjAtBoundary = EDGE;
955
	    bound.neighbourObject.ithObjAtBoundary = elInfo->getSideOfNeighbour(i);
956
	    
957
958
959
	    // i == 2  =>  getSideOfNeighbour(i) == 2
	    TEST_EXIT_DBG(i != 2 || elInfo->getSideOfNeighbour(i) == 2)
	      ("Should not happen!\n");
960
961
962
963
964
965
966
967
968
969
970
971
972
973

	    int otherElementRank = partitionVec[elInfo->getNeighbour(i)->getIndex()];

	    if (BoundaryManager::isBoundaryPeriodic(elInfo->getBoundary(i))) {	      
	      // We have found an element that is at an interior, periodic boundary.
	      AtomicBoundary& b = periodicBoundary.getNewAtomic(otherElementRank);
	      b = bound;
	    } else {
	      // We have found an element that is at an interior, non-periodic boundary.
	      AtomicBoundary& b = ((mpiRank > otherElementRank) ?
				   myIntBoundary.getNewAtomic(otherElementRank) :
				   otherIntBoundary.getNewAtomic(otherElementRank));
	      b = bound;	      
	    }
974
975
976
977
978
979
 	  }
	}
      }

      elInfo = stack.traverseNext(elInfo);
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
980
981

    // === Once we have this information, we must care about their order. Eventually ===
Thomas Witkowski's avatar
Thomas Witkowski committed
982
983
    // === all the boundaries have to be in the same order on both ranks that share  ===
    // === the bounday.                                                              ===
Thomas Witkowski's avatar
Thomas Witkowski committed
984

Thomas Witkowski's avatar
Thomas Witkowski committed
985
    std::vector<int*> sendBuffers, recvBuffers;
Thomas Witkowski's avatar
Thomas Witkowski committed
986

987
988
989
    MPI::Request request[max(myIntBoundary.boundary.size() + 
			     otherIntBoundary.boundary.size(),
			     periodicBoundary.boundary.size())];
Thomas Witkowski's avatar
Thomas Witkowski committed
990
991
    int requestCounter = 0;

Thomas Witkowski's avatar
Thomas Witkowski committed
992
993
    for (RankToBoundMap::iterator rankIt = myIntBoundary.boundary.begin();
	 rankIt != myIntBoundary.boundary.end(); ++rankIt) {    
Thomas Witkowski's avatar
Thomas Witkowski committed
994
      int nSendInt = rankIt->second.size();
995
996
997
998
999
      int* buffer = new int[nSendInt * 2];
      for (int i = 0; i < nSendInt; i++) {
	buffer[i * 2] = (rankIt->second)[i].rankObject.elIndex;
	buffer[i * 2 + 1] = (rankIt->second)[i].rankObject.ithObjAtBoundary;
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
1000
1001
      sendBuffers.push_back(buffer);
      
Thomas Witkowski's avatar
Thomas Witkowski committed
1002
      request[requestCounter++] =
1003
	mpiComm.Isend(buffer, nSendInt * 2, MPI_INT, rankIt->first, 0);
Thomas Witkowski's avatar
Thomas Witkowski committed
1004
1005
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
1006
1007
    for (RankToBoundMap::iterator rankIt = otherIntBoundary.boundary.begin();
	 rankIt != otherIntBoundary.boundary.end(); ++rankIt) {
Thomas Witkowski's avatar
Thomas Witkowski committed
1008
      int nRecvInt = rankIt->second.size();
1009
      int *buffer = new int[nRecvInt * 2];
Thomas Witkowski's avatar
Thomas Witkowski committed
1010
      recvBuffers.push_back(buffer);
Thomas Witkowski's avatar
Thomas Witkowski committed
1011

Thomas Witkowski's avatar
Thomas Witkowski committed
1012
      request[requestCounter++] = 
1013
	mpiComm.Irecv(buffer, nRecvInt * 2, MPI_INT, rankIt->first, 0);
Thomas Witkowski's avatar
Thomas Witkowski committed
1014
1015
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
1016
1017
1018

    MPI::Request::Waitall(requestCounter, request);

Thomas Witkowski's avatar
Thomas Witkowski committed
1019
1020

    int i = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
1021
1022
    for (RankToBoundMap::iterator rankIt = otherIntBoundary.boundary.begin();
	 rankIt != otherIntBoundary.boundary.end(); ++rankIt) {
Thomas Witkowski's avatar
Thomas Witkowski committed
1023
1024
1025
1026
1027
1028
1029

      // === We have received from rank "rankIt->first" the ordered list of element ===
      // === indices. We now have to sort the corresponding list in this rank to    ===
      // === get the same order.                                                    ===
      
      for (int j = 0; j < static_cast<int>(rankIt->second.size()); j++) {
	// If the expected object is not at place, search for it.
1030
1031
	if ((rankIt->second)[j].neighbourObject.elIndex != recvBuffers[i][j * 2] ||
	    (rankIt->second)[j].neighbourObject.ithObjAtBoundary != recvBuffers[i][j * 2 + 1]) {
Thomas Witkowski's avatar
Thomas Witkowski committed
1032
1033
	  int k = j + 1;
	  for (; k < static_cast<int>(rankIt->second.size()); k++)
1034
1035
	    if ((rankIt->second)[k].neighbourObject.elIndex == recvBuffers[i][j * 2] && 
		(rankIt->second)[k].neighbourObject.ithObjAtBoundary == recvBuffers[i][j * 2 + 1])
Thomas Witkowski's avatar
Thomas Witkowski committed
1036
1037
1038
	      break;

	  // The element must always be found, because the list is just in another order.
Thomas Witkowski's avatar
Thomas Witkowski committed
1039
	  TEST_EXIT_DBG(k < static_cast<int>(rankIt->second.size()))
1040
	    ("Should never happen!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
1041
1042
1043
1044
1045
1046
1047
1048

	  // Swap the current with the found element.
	  AtomicBoundary tmpBound = (rankIt->second)[k];
	  (rankIt->second)[k] = (rankIt->second)[j];
	  (rankIt->second)[j] = tmpBound;	
	}
      }

1049
1050
      delete [] recvBuffers[i];
      i++;
Thomas Witkowski's avatar
Thomas Witkowski committed
1051
1052
1053
1054
    }

    for (int i = 0; i < static_cast<int>(sendBuffers.size()); i++)
      delete [] sendBuffers[i];
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126

    recvBuffers.clear();
    sendBuffers.clear();
 

    // === Deal with periodic boundaries. ===

    requestCounter = 0;

    for (RankToBoundMap::iterator rankIt = periodicBoundary.boundary.begin();
	 rankIt != periodicBoundary.boundary.end(); ++rankIt) {

      TEST_EXIT_DBG(rankIt->first != mpiRank)
	("It is no possible to have an interior boundary within a rank partition!\n");

      if (rankIt->first < mpiRank) {
	int nSendInt = rankIt->second.size();
	int* buffer = new int[nSendInt * 2];
	for (int i = 0; i < nSendInt; i++) {
	  buffer[i * 2] = (rankIt->second)[i].rankObject.elIndex;
	  buffer[i * 2 + 1] = (rankIt->second)[i].rankObject.ithObjAtBoundary;
	}
	sendBuffers.push_back(buffer);

	request[requestCounter++] =
	  mpiComm.Isend(buffer, nSendInt * 2, MPI_INT, rankIt->first, 0);
      } else {
	int nRecvInt = rankIt->second.size();
	int *buffer = new int[nRecvInt * 2];
	recvBuffers.push_back(buffer);
	
	request[requestCounter++] = 
	  mpiComm.Irecv(buffer, nRecvInt * 2, MPI_INT, rankIt->first, 0);	
      }
    }


    MPI::Request::Waitall(requestCounter, request);


    i = 0;
    for (RankToBoundMap::iterator rankIt = periodicBoundary.boundary.begin();
	 rankIt != periodicBoundary.boundary.end(); ++rankIt) {
      if (rankIt->first > mpiRank) {

	for (int j = 0; j < static_cast<int>(rankIt->second.size()); j++) 
	  if (periodicBoundary.boundary[rankIt->first][j].neighbourObject.elIndex != recvBuffers[i][j * 2] ||
	      periodicBoundary.boundary[rankIt->first][j].neighbourObject.ithObjAtBoundary != recvBuffers[i][j * 2 + 1]) {
	    int k = j + 1;

	    for (; k < static_cast<int>(rankIt->second.size()); k++)
	      if (periodicBoundary.boundary[rankIt->first][k].neighbourObject.elIndex == recvBuffers[i][j * 2] && 
		  periodicBoundary.boundary[rankIt->first][k].neighbourObject.ithObjAtBoundary == recvBuffers[i][j * 2 + 1])
		break;

	    // The element must always be found, because the list is just in another order.
	    TEST_EXIT_DBG(k < static_cast<int>(rankIt->second.size()))
	      ("Should never happen!\n");
	    
	    // Swap the current with the found element.
	    AtomicBoundary tmpBound = (rankIt->second)[k];
	    (rankIt->second)[k] = (rankIt->second)[j];
	    (rankIt->second)[j] = tmpBound;	
	  }

	delete [] recvBuffers[i];
	i++;
      }
    }

    for (int i = 0; i < static_cast<int>(sendBuffers.size()); i++)
      delete [] sendBuffers[i]; 
1127
1128
1129
  }


1130
  void ParallelDomainBase::removeMacroElements()
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
  {
    std::vector<MacroElement*> macrosToRemove;
    for (std::deque<MacroElement*>::iterator it = mesh->firstMacroElement();
	 it != mesh->endOfMacroElements();
	 ++it) {
      PartitionElementData *partitionData = 
	dynamic_cast<PartitionElementData*>
	((*it)->getElement()->getElementData(PARTITION_ED));
      if (partitionData->getPartitionStatus() != IN)
	macrosToRemove.push_back(*it);
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
1143
    mesh->removeMacroElements(macrosToRemove, feSpace);
1144
1145
1146
  }


1147
  void ParallelDomainBase::createLocalGlobalNumbering(DofContainer& rankDofs,
1148
						      int& nRankDofs, 
Thomas Witkowski's avatar
Thomas Witkowski committed
1149
						      int& nOverallDOFs)
1150
  {
1151
    FUNCNAME("ParallelDomainBase::createLocalGlobalNumbering()");
1152
1153

    // === Get rank information about DOFs. ===
1154
1155
1156

    // Stores to each DOF pointer the set of ranks the DOF is part of.
    std::map<const DegreeOfFreedom*, std::set<int> > partitionDOFs;
Thomas Witkowski's avatar
n    
Thomas Witkowski committed
1157
    DofContainer rankAllDofs;
1158
    DofToRank boundaryDofs;
1159

1160
    createDofMemberInfo(partitionDOFs, rankDofs, rankAllDofs, boundaryDofs, vertexDof);
1161

1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
    // === BEGIN EXP

    DofIndexToBool rankAllDofIndices;
    for (DofContainer::iterator dofIt = rankAllDofs.begin(); 
	 dofIt != rankAllDofs.end(); ++dofIt) {
      rankAllDofIndices[**dofIt] = true;
    }

    for (std::map<BoundaryType, VertexVector*>::iterator it = mesh->getPeriodicAssociations().begin();
	 it != mesh->getPeriodicAssociations().end(); ++it) {
      VertexVector *tmp = it->second;
      DOFIteratorBase it(const_cast<DOFAdmin*>(tmp->getAdmin()), USED_DOFS);
      for (it.reset(); !it.end(); ++it) {
	if (!it.isDOFFree()) {
	  if (!rankAllDofIndices[(*tmp)[it.getDOFIndex()]] &&
	      rankAllDofIndices[it.getDOFIndex()])
	    //	    (*tmp)[it.getDOFIndex()] = -1;
	    (*tmp)[it.getDOFIndex()] = it.getDOFIndex();
	}
      }
    }
    
    // === ENDE EXP

1186
    nRankDofs = rankDofs.size();
1187
1188
    nOverallDOFs = partitionDOFs.size();

1189