PetscSolverGlobalMatrix.cc 23.2 KB
Newer Older
Thomas Witkowski's avatar
Thomas Witkowski committed
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.


13
#include "AMDiS.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
14
15
16
17
18
19
#include "parallel/PetscSolverGlobalMatrix.h"
#include "parallel/StdMpi.h"
#include "parallel/MpiHelper.h"

namespace AMDiS {

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
20
  void PetscSolverGlobalMatrix::fillPetscMatrix(Matrix<DOFMatrix*> *seqMat)
Thomas Witkowski's avatar
Thomas Witkowski committed
21
22
23
  {
    FUNCNAME("PetscSolverGlobalMatrix::fillPetscMatrix()");

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
24
25
26
27
28
29
    TEST_EXIT_DBG(meshDistributor)("No mesh distributor object defined!\n");
    TEST_EXIT_DBG(interiorMap)("No parallel mapping object defined!\n");
    TEST_EXIT_DBG(seqMat)("No DOF matrix defined!\n");
    
    double wtime = MPI::Wtime();

30
31
32
    petscData.init(interiorMap, coarseSpaceMap, 
		   subdomainLevel, mpiCommLocal, mpiCommGlobal,
		   meshDistributor);
Thomas Witkowski's avatar
Thomas Witkowski committed
33
    petscData.create(*seqMat);
34

Thomas Witkowski's avatar
Thomas Witkowski committed
35
    if (coarseSpaceMap.size()) {
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
36
      fillPetscMatrixWithCoarseSpace(seqMat);
37
38
39
      return;
    }

40
41
    // === Create PETSc vector (solution and a temporary vector). ===

Thomas Witkowski's avatar
Thomas Witkowski committed
42
43
44
45
46
47
#if (DEBUG != 0)
    MSG("Fill petsc matrix 1 needed %.5f seconds\n", MPI::Wtime() - wtime);
#endif

    // === Transfer values from DOF matrices to the PETSc matrix. === 

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
48
    int nComponents = seqMat->getNumRows();
Thomas Witkowski's avatar
Thomas Witkowski committed
49
50
    for (int i = 0; i < nComponents; i++)
      for (int j = 0; j < nComponents; j++)
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
51
52
	if ((*seqMat)[i][j])
	  setDofMatrix((*seqMat)[i][j], i, j);
Thomas Witkowski's avatar
Thomas Witkowski committed
53
54
55
56
57

#if (DEBUG != 0)
    MSG("Fill petsc matrix 2 needed %.5f seconds\n", MPI::Wtime() - wtime);
#endif

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
58
    petscData.matAssembly();
59
60
61
    
    if (printMatInfo) {
      MatInfo matInfo;
62
      MatGetInfo(petscData.getInteriorMat(), MAT_GLOBAL_SUM, &matInfo);
63
64
65
66
67
68
69
      MSG("Matrix info:\n");
      MSG("  memory usage: %e MB\n", matInfo.memory / (1024.0 * 1024.0));
      MSG("  mallocs: %d\n", static_cast<int>(matInfo.mallocs));
      MSG("  nz allocated: %d\n", static_cast<int>(matInfo.nz_allocated));
      MSG("  nz used: %d\n", static_cast<int>(matInfo.nz_used));
      MSG("  nz unneeded: %d\n", static_cast<int>(matInfo.nz_unneeded));
    }
70
71
72

    // === Remove Dirichlet BC DOFs. ===

73
    //    removeDirichletBcDofs(mat);
74
75
    

76
    // === Init PETSc solver. ===
77

78
79
    KSPCreate(mpiCommGlobal, &kspInterior);
    KSPGetPC(kspInterior, &pcInterior);
80
81
82
83
    KSPSetOperators(kspInterior, 
		    petscData.getInteriorMat(), 
		    petscData.getInteriorMat(), 
		    SAME_NONZERO_PATTERN); 
84
85
86
87
    KSPSetTolerances(kspInterior, 0.0, 1e-8, PETSC_DEFAULT, PETSC_DEFAULT);
    KSPSetType(kspInterior, KSPBCGS);
    KSPSetOptionsPrefix(kspInterior, kspPrefix.c_str());
    KSPSetFromOptions(kspInterior);
88

89
    initPreconditioner(pcInterior);
90

91
92
    // Do not delete the solution vector, use it for the initial guess.
    if (!zeroStartVector)
93
      KSPSetInitialGuessNonzero(kspInterior, PETSC_TRUE);
94

Thomas Witkowski's avatar
Thomas Witkowski committed
95
96
97
#if (DEBUG != 0)
    MSG("Fill petsc matrix 3 needed %.5f seconds\n", MPI::Wtime() - wtime);
#endif
98
99
100
  }


101
102
103
104
105
106
107
108
  void PetscSolverGlobalMatrix::fillPetscMatrix(DOFMatrix *mat)
  {
    Matrix<DOFMatrix*> m(1, 1);
    m[0][0] = mat;
    fillPetscMatrix(&m);
  }


Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
109
  void PetscSolverGlobalMatrix::fillPetscMatrixWithCoarseSpace(Matrix<DOFMatrix*> *seqMat)
110
111
  {
    FUNCNAME("PetscSolverGlobalMatrix::fillPetscMatrixWithCoarseSpace()");
112
113

    TEST_EXIT_DBG(interiorMap)("Should not happen!\n");
114
115
    TEST_EXIT_DBG(coarseSpaceMap.size() == seqMat->getSize())
      ("Wrong sizes %d %d\n", coarseSpaceMap.size(), seqMat->getSize());
116

Thomas Witkowski's avatar
Thomas Witkowski committed
117
    vector<const FiniteElemSpace*> feSpaces = AMDiS::getFeSpaces(*seqMat);
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
118

119
120
    int nRowsRankInterior = interiorMap->getRankDofs();
    int nRowsOverallInterior = interiorMap->getOverallDofs();
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
121
    int rStartInterior = petscData.getStartInterior();
122

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    // === Prepare traverse of sequentially created matrices. ===

    using mtl::tag::row; using mtl::tag::nz; using mtl::begin; using mtl::end;
    namespace traits = mtl::traits;
    typedef DOFMatrix::base_matrix_type Matrix;

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

    vector<int> cols, colsOther;
    vector<double> values, valuesOther;
    cols.reserve(300);
    colsOther.reserve(300);
    values.reserve(300);
    valuesOther.reserve(300);

    // === Traverse all sequentially created matrices and add the values to ===
    // === the global PETSc matrices.                                       ===

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
142
    int nComponents = seqMat->getSize();
143
144
    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++) {
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
145
	if (!(*seqMat)[i][j])
146
147
	  continue;

Thomas Witkowski's avatar
Thomas Witkowski committed
148
149
150
	ParallelDofMapping *rowCoarseSpace = coarseSpaceMap[i];
	ParallelDofMapping *colCoarseSpace = coarseSpaceMap[j];

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
151
152
	traits::col<Matrix>::type col((*seqMat)[i][j]->getBaseMatrix());
	traits::const_value<Matrix>::type value((*seqMat)[i][j]->getBaseMatrix());
153
154
	
	// Traverse all rows.
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
155
156
	for (cursor_type cursor = begin<row>((*seqMat)[i][j]->getBaseMatrix()), 
	       cend = end<row>((*seqMat)[i][j]->getBaseMatrix()); cursor != cend; ++cursor) {
157

Thomas Witkowski's avatar
Thomas Witkowski committed
158
	  bool isRowCoarse = isCoarseSpace(i, feSpaces[i], *cursor);
159
160
161
162
163
164
165
166
167
168
  
	  cols.clear();
	  colsOther.clear();
	  values.clear();	  
	  valuesOther.clear();

	  // Traverse all columns.
	  for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor); 
	       icursor != icend; ++icursor) {

Thomas Witkowski's avatar
Thomas Witkowski committed
169
	    bool isColCoarse = isCoarseSpace(j, feSpaces[j], col(*icursor));
170

Thomas Witkowski's avatar
Thomas Witkowski committed
171
172
	    if (isColCoarse) {
	      if (isRowCoarse) {
173
174
175
176
177
178
179
		cols.push_back(col(*icursor));
		values.push_back(value(*icursor));
	      } else {
		colsOther.push_back(col(*icursor));
		valuesOther.push_back(value(*icursor));
	      }
	    } else {
Thomas Witkowski's avatar
Thomas Witkowski committed
180
	      if (isRowCoarse) {
181
182
183
184
185
186
187
188
189
190
191
192
		colsOther.push_back(col(*icursor));
		valuesOther.push_back(value(*icursor));
	      } else {
		cols.push_back(col(*icursor));
		values.push_back(value(*icursor));
	      }
	    }
	  }  // for each nnz in row


	  // === Set matrix values. ===

Thomas Witkowski's avatar
Thomas Witkowski committed
193
194
	  if (isRowCoarse) {
	    int rowIndex = rowCoarseSpace->getMatIndex(i, *cursor);
195
	    for (unsigned int k = 0; k < cols.size(); k++)
Thomas Witkowski's avatar
Thomas Witkowski committed
196
	      cols[k] = colCoarseSpace->getMatIndex(j, cols[k]);
197

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
198
	    // matCoarseCoarse
199
	    MatSetValues(petscData.getCoarseMatComp(i),
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
200
			 1, &rowIndex, cols.size(),
201
202
203
204
			 &(cols[0]), &(values[0]), ADD_VALUES);

	    if (colsOther.size()) {
	      if (subdomainLevel == 0) {
205
		for (unsigned int k = 0; k < colsOther.size(); k++)
206
207
208
209
210
211
		  colsOther[k] = interiorMap->getMatIndex(j, colsOther[k]);
	      } else {
		for (unsigned int k = 0; k < colsOther.size(); k++)
		  colsOther[k] = 
		    interiorMap->getMatIndex(j, colsOther[k]) + rStartInterior;
	      }
212

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
213
	      // matCoarseInt
214
	      MatSetValues(petscData.getCoarseIntMatComp(i), 
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
215
			   1, &rowIndex, colsOther.size(),
216
217
218
219
220
221
222
223
224
225
226
227
228
229
 			   &(colsOther[0]), &(valuesOther[0]), ADD_VALUES);
	    }
	  } else {
	    int localRowIndex = 
	      (subdomainLevel == 0 ? interiorMap->getLocalMatIndex(i, *cursor) :
	       interiorMap->getMatIndex(i, *cursor));

	    for (unsigned int k = 0; k < cols.size(); k++) {
	      if (subdomainLevel == 0)
		cols[k] = interiorMap->getLocalMatIndex(j, cols[k]);
	      else
		cols[k] = interiorMap->getMatIndex(j, cols[k]);
	    }
	    
230
  	    MatSetValues(petscData.getInteriorMat(), 1, &localRowIndex, cols.size(),
231
232
233
234
235
236
237
238
239
  			 &(cols[0]), &(values[0]), ADD_VALUES);

	    if (colsOther.size()) {
	      int globalRowIndex = interiorMap->getMatIndex(i, *cursor);

	      if (subdomainLevel != 0)
		globalRowIndex += rStartInterior;

	      for (unsigned int k = 0; k < colsOther.size(); k++)
Thomas Witkowski's avatar
Thomas Witkowski committed
240
		colsOther[k] = colCoarseSpace->getMatIndex(j, colsOther[k]);
241

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
242
	      // matIntCoarse
243
  	      MatSetValues(petscData.getIntCoarseMatComp(i), 
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
244
			   1, &globalRowIndex, colsOther.size(),
245
246
247
248
249
250
251
  			   &(colsOther[0]), &(valuesOther[0]), ADD_VALUES);
	    }
	  }
	} 
      }
    }

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
252
    petscData.matAssembly();
253

254
255
256
    // === Create solver for the non primal (thus local) variables. ===

    KSPCreate(mpiCommLocal, &kspInterior);
257
258
259
260
    KSPSetOperators(kspInterior, 
		    petscData.getInteriorMat(),
		    petscData.getInteriorMat(),
		    SAME_NONZERO_PATTERN);
261
262
263
264
265
266
267
268
269
270
271
272
    KSPSetOptionsPrefix(kspInterior, "interior_");
    KSPSetType(kspInterior, KSPPREONLY);
    KSPGetPC(kspInterior, &pcInterior);
    PCSetType(pcInterior, PCLU);
    if (subdomainLevel == 0)
      PCFactorSetMatSolverPackage(pcInterior, MATSOLVERUMFPACK);
    else
      PCFactorSetMatSolverPackage(pcInterior, MATSOLVERMUMPS);
    KSPSetFromOptions(kspInterior);  
  }


273
274
275
  void PetscSolverGlobalMatrix::fillPetscRhs(SystemVector *vec)
  {
    FUNCNAME("PetscSolverGlobalMatrix::fillPetscRhs()");
Thomas Witkowski's avatar
Thomas Witkowski committed
276

277
    TEST_EXIT_DBG(vec)("No DOF vector defined!\n");
278
    TEST_EXIT_DBG(interiorMap)("No parallel DOF map defined!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
279
    
Thomas Witkowski's avatar
Thomas Witkowski committed
280
    // === Transfer values from DOF vector to the PETSc vector. === 
Thomas Witkowski's avatar
Thomas Witkowski committed
281
    if (coarseSpaceMap.size()) {
Thomas Witkowski's avatar
Thomas Witkowski committed
282
      for (int i = 0; i < vec->getSize(); i++)
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
283
	setDofVector(getRhsInterior(), getRhsCoarseSpace(), vec->getDOFVector(i), i);
Thomas Witkowski's avatar
Thomas Witkowski committed
284
285
    } else {
      for (int i = 0; i < vec->getSize(); i++)
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
286
	setDofVector(getRhsInterior(), vec->getDOFVector(i), i);
Thomas Witkowski's avatar
Thomas Witkowski committed
287
288
    }

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
289
    petscData.vecRhsAssembly();
Thomas Witkowski's avatar
Thomas Witkowski committed
290
291
292
  }


293
294
  void PetscSolverGlobalMatrix::solvePetscMatrix(SystemVector &vec, 
						 AdaptInfo *adaptInfo)
Thomas Witkowski's avatar
Thomas Witkowski committed
295
296
297
298
299
300
301
  {
    FUNCNAME("PetscSolverGlobalMatrix::solvePetscMatrix()");

    int nComponents = vec.getSize();

    // === Set old solution to be initiual guess for PETSc solver. ===
    if (!zeroStartVector) {
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
302
303
304
      TEST_EXIT(coarseSpaceMap.size() == 0)("Not yet supported!\n");

      VecSet(getSolInterior(), 0.0);
Thomas Witkowski's avatar
Thomas Witkowski committed
305
306
      
      for (int i = 0; i < nComponents; i++)
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
307
308
309
	setDofVector(getSolInterior(), vec.getDOFVector(i), i, true);

      petscData.vecSolAssembly();
Thomas Witkowski's avatar
Thomas Witkowski committed
310
311
    }

312

Thomas Witkowski's avatar
Thomas Witkowski committed
313
314
    MatNullSpace matNullspace;
    Vec nullspaceBasis;
315
316
317
    if (nullspace.size() > 0 || 
	hasConstantNullspace ||
	constNullspaceComponent.size() > 0) {
Thomas Witkowski's avatar
Thomas Witkowski committed
318
      TEST_EXIT_DBG(nullspace.size() <= 1)("Not yet implemented!\n");
319

320
321
322
323
324
325
326
327
328
329
      if (constNullspaceComponent.size() > 0) {
	nullspace.clear();
	SystemVector *basisVec = new SystemVector(vec);
	basisVec->set(0.0);
	for (unsigned int i = 0; i < constNullspaceComponent.size(); i++)
	  basisVec->getDOFVector(constNullspaceComponent[i])->set(1.0);

	nullspace.push_back(basisVec);
      } 

Thomas Witkowski's avatar
Thomas Witkowski committed
330
      if (nullspace.size() > 0) {
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
331
	VecDuplicate(getSolInterior(), &nullspaceBasis);
Thomas Witkowski's avatar
Thomas Witkowski committed
332
333
334
335
336
	for (int i = 0; i < nComponents; i++)
	  setDofVector(nullspaceBasis, nullspace[0]->getDOFVector(i), i, true);
	
	VecAssemblyBegin(nullspaceBasis);
	VecAssemblyEnd(nullspaceBasis);
337
338

	VecNormalize(nullspaceBasis, PETSC_NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
339
340
341
342
	
	MatNullSpaceCreate(mpiCommGlobal, (hasConstantNullspace ? PETSC_TRUE : PETSC_FALSE), 
			   1, &nullspaceBasis, &matNullspace);

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
343
	MatMult(petscData.getInteriorMat(), nullspaceBasis, getSolInterior());
Thomas Witkowski's avatar
Thomas Witkowski committed
344
	PetscReal n;
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
345
	VecNorm(getSolInterior(), NORM_2, &n);
Thomas Witkowski's avatar
Thomas Witkowski committed
346
347
348
349
	MSG("NORM IS: %e\n", n);
      } else {
	MatNullSpaceCreate(mpiCommGlobal, PETSC_TRUE, 0, PETSC_NULL, &matNullspace);
      }
350

351
      MatSetNullSpace(petscData.getInteriorMat(), matNullspace);
Thomas Witkowski's avatar
Thomas Witkowski committed
352
      KSPSetNullSpace(kspInterior, matNullspace);
353

Thomas Witkowski's avatar
Thomas Witkowski committed
354
      // === Remove null space, if requested. ===
355

Thomas Witkowski's avatar
Thomas Witkowski committed
356
      if (removeRhsNullspace) {
Thomas Witkowski's avatar
Thomas Witkowski committed
357
	TEST_EXIT_DBG(coarseSpaceMap.empty())("Not supported!\n");
358
359

	MSG("Remove nullspace from rhs vector.\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
360
	
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
361
	MatNullSpaceRemove(matNullspace, getRhsInterior(), PETSC_NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
362
363
364
365
      }
    } else {
      TEST_EXIT(removeRhsNullspace == false)
	("No nullspace provided that should be removed from rhs!\n");
366
367
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
368
    // PETSc.
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
369
    solve(getRhsInterior(), getSolInterior());
Thomas Witkowski's avatar
Thomas Witkowski committed
370

371
372

    if (nullspace.size() > 0) {
Thomas Witkowski's avatar
Thomas Witkowski committed
373
      MatNullSpaceDestroy(&matNullspace);
374
375
376
377
      VecDestroy(&nullspaceBasis);
    }


Thomas Witkowski's avatar
Thomas Witkowski committed
378
379
    // === Transfere values from PETSc's solution vectors to the DOF vectors. ===
    PetscScalar *vecPointer;
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
380
    VecGetArray(getSolInterior(), &vecPointer);    
Thomas Witkowski's avatar
Thomas Witkowski committed
381

382
    int c = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
383
    for (int i = 0; i < nComponents; i++) {
384
      DOFVector<double> &dv = *(vec.getDOFVector(i));
385

386
      DofMap& d = (*interiorMap)[dv.getFeSpace()].getMap();
387
388
389
      for (DofMap::iterator it = d.begin(); it != d.end(); ++it)
	if (it->second.local != -1)
	  dv[it->first] = vecPointer[c++];
Thomas Witkowski's avatar
Thomas Witkowski committed
390
391
    }

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
392
    VecRestoreArray(getSolInterior(), &vecPointer);
Thomas Witkowski's avatar
Thomas Witkowski committed
393
394
395
396

    // === Synchronize DOFs at common DOFs, i.e., DOFs that correspond to ===  
    // === more than one partition.                                       ===  
    meshDistributor->synchVector(vec);
397
398
399
  }


400
401
402
403
  void PetscSolverGlobalMatrix::solveGlobal(Vec &rhs, Vec &sol)
  {
    FUNCNAME("PetscSolverGlobalMatrix::solveGlobal()");

404
405
406
    double wtime = MPI::Wtime();
    double t0 = 0.0, t1 = 0.0;

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
    Vec tmp;
    if (mpiCommLocal.Get_size() == 1)
      VecCreateSeq(mpiCommLocal, interiorMap->getRankDofs(), &tmp);
    else
      VecCreateMPI(mpiCommLocal,
		   interiorMap->getRankDofs(),
		   interiorMap->getOverallDofs(),
		   &tmp);

    PetscScalar *tmpValues, *rhsValues;
    VecGetArray(tmp, &tmpValues);
    VecGetArray(rhs, &rhsValues);

    for (int i = 0; i < interiorMap->getRankDofs(); i++)
      tmpValues[i] = rhsValues[i];

    VecRestoreArray(rhs, &rhsValues);
    VecRestoreArray(tmp, &tmpValues);

426
427
428
    t0 = MPI::Wtime() - wtime;

    wtime = MPI::Wtime();
429
    KSPSolve(kspInterior, tmp, tmp);
430
431
432
    t1 = MPI::Wtime() - wtime;

    wtime = MPI::Wtime();
433
434
435
436
437
438
439
440
441
442
443

    VecGetArray(tmp, &tmpValues);
    VecGetArray(sol, &rhsValues);

    for (int i = 0; i < interiorMap->getRankDofs(); i++) 
      rhsValues[i] = tmpValues[i];

    VecRestoreArray(sol, &rhsValues);
    VecRestoreArray(tmp, &tmpValues);

    VecDestroy(&tmp);
444
445
    t0 += MPI::Wtime() - wtime;

446
    //    MSG("TIMEING: %.5f %.5f\n", t0, t1);
447
448
449
  }


450
451
452
453
  void PetscSolverGlobalMatrix::destroyMatrixData()
  {
    FUNCNAME("PetscSolverGlobalMatrix::destroyMatrixData()");

454
455
    exitPreconditioner(pcInterior);

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
456
    petscData.matDestroy();
Thomas Witkowski's avatar
Thomas Witkowski committed
457

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
458
    KSPDestroy(&kspInterior);
Thomas Witkowski's avatar
Thomas Witkowski committed
459
460
461
  }


462
463
464
465
  void PetscSolverGlobalMatrix::destroyVectorData()
  {
    FUNCNAME("PetscSolverGlobalMatrix::destroyVectorData()");

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
466
    petscData.vecDestroy();
467
468
469
  }


470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
  void PetscSolverGlobalMatrix::createFieldSplit(PC pc)
  {
    FUNCNAME("PetscSolverGlobalMatrix::createFieldSplit()");

    vector<string> isNames;
    Parameters::get("parallel->solver->is blocks", isNames);

    int nBlocks = isNames.size();
    if (nBlocks == 0)
      return;

    for (int i = 0; i < nBlocks; i++) {
      MSG("Create for block %s\n", isNames[i].c_str());

      vector<int> blockComponents;
      Parameters::get("parallel->solver->is block " + lexical_cast<string>(i),
		      blockComponents);
      int nComponents = static_cast<int>(blockComponents.size());

      TEST_EXIT(nComponents > 0)("No is block for block %d defined!\n", i);

      // Check if blocks are continous
      for (int j = 0; j < nComponents; j++) {
	TEST_EXIT(blockComponents[j] == blockComponents[0] + j)
	  ("Does not yet support not continous IS blocks! Block %s\n", 
	   isNames[i].c_str());
      }

      IS is;
      interiorMap->createIndexSet(is, blockComponents[0], nComponents);
      PCFieldSplitSetIS(pc, isNames[i].c_str(), is);
      ISDestroy(&is);
    }
  }


506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
  void PetscSolverGlobalMatrix::initPreconditioner(PC pc)
  {
    FUNCNAME("PetscSolverGlobalMatrix::initPreconditioner()");

    PCSetFromOptions(pc);
    createFieldSplit(pc);
  }

 
  void PetscSolverGlobalMatrix::exitPreconditioner(PC pc)
  {
    FUNCNAME("PetscSolverGlobalMatrix::exitPreconditioner()");
  }


Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
521
  void PetscSolverGlobalMatrix::setDofMatrix(DOFMatrix* seqMat,
522
					     int nRowMat, int nColMat)
Thomas Witkowski's avatar
Thomas Witkowski committed
523
524
525
  {
    FUNCNAME("PetscSolverGlobalMatrix::setDofMatrix()");

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
526
    TEST_EXIT(seqMat)("No DOFMatrix!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
527
528

    using mtl::tag::row; using mtl::tag::nz; using mtl::begin; using mtl::end;
529
    namespace traits = mtl::traits;
Thomas Witkowski's avatar
Thomas Witkowski committed
530
531
    typedef DOFMatrix::base_matrix_type Matrix;

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
532
533
    traits::col<Matrix>::type col(seqMat->getBaseMatrix());
    traits::const_value<Matrix>::type value(seqMat->getBaseMatrix());
Thomas Witkowski's avatar
Thomas Witkowski committed
534
535
536
537
538
539
540
541
542
543
544

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

    vector<int> cols;
    vector<double> values;
    cols.reserve(300);
    values.reserve(300);
    
    vector<int> globalCols;

545
546
547
    // Get periodic mapping object
    PeriodicMap &perMap = meshDistributor->getPeriodicMap();

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
548
549
    const FiniteElemSpace *rowFe = seqMat->getRowFeSpace();
    const FiniteElemSpace *colFe = seqMat->getColFeSpace();
Thomas Witkowski's avatar
Thomas Witkowski committed
550
551
552
553
    DofMap& rowMap = (*interiorMap)[rowFe].getMap();
    DofMap& colMap = (*interiorMap)[colFe].getMap();

    // === Traverse all rows of the DOF matrix and insert row wise the values ===
Thomas Witkowski's avatar
Thomas Witkowski committed
554
555
    // === to the PETSc matrix.                                               ===

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
556
557
    for (cursor_type cursor = begin<row>(seqMat->getBaseMatrix()), 
	   cend = end<row>(seqMat->getBaseMatrix()); cursor != cend; ++cursor) {
Thomas Witkowski's avatar
Thomas Witkowski committed
558
      // Global index of the current row DOF.
Thomas Witkowski's avatar
Thomas Witkowski committed
559
      int globalRowDof = rowMap[*cursor].global;
560

Thomas Witkowski's avatar
Thomas Witkowski committed
561
      // Test if the current row DOF is a periodic DOF.
562
      bool periodicRow = perMap.isPeriodic(rowFe, globalRowDof);
563

Thomas Witkowski's avatar
Thomas Witkowski committed
564
565
566
      if (!periodicRow) {
	// === Row DOF index is not periodic. ===

567
	// Get PETSc's mat row index.
568
	int rowIndex = interiorMap->getMatIndex(nRowMat, globalRowDof);
Thomas Witkowski's avatar
Thomas Witkowski committed
569
570
571
572
573
574
575
576

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

	for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor); 
	     icursor != icend; ++icursor) {

	  // Global index of the current column index.
Thomas Witkowski's avatar
Thomas Witkowski committed
577
	  int globalColDof = colMap[col(*icursor)].global;
Thomas Witkowski's avatar
Thomas Witkowski committed
578
	  // Test if the current col dof is a periodic dof.
579
	  bool periodicCol = perMap.isPeriodic(colFe, globalColDof);
580
	  // Get PETSc's mat col index.
581
	  int colIndex = interiorMap->getMatIndex(nColMat, globalColDof);
Thomas Witkowski's avatar
Thomas Witkowski committed
582
583
584
585
586
587
588

	  // Ignore all zero entries, expect it is a diagonal entry.
 	  if (value(*icursor) == 0.0 && rowIndex != colIndex)
 	    continue;

	  if (!periodicCol) {
	    // Calculate the exact position of the column index in the PETSc matrix.
Thomas Witkowski's avatar
Thomas Witkowski committed
589
590
 	    cols.push_back(colIndex);
 	    values.push_back(value(*icursor));
Thomas Witkowski's avatar
Thomas Witkowski committed
591
592
593
594
595
	  } else {
	    // === Row index is not periodic, but column index is. ===

	    // Create set of all periodic associations of the column index.
	    std::set<int> perAsc;
596
597
598
	    perMap.fillAssociations(colFe, globalColDof, 
				    meshDistributor->getElementObjectDb(), perAsc);

Thomas Witkowski's avatar
Thomas Witkowski committed
599
600
601
602
603
604
605
606
607
	    // Scale value to the number of periodic associations of the column index.
	    double scaledValue = 
	      value(*icursor) * pow(0.5, static_cast<double>(perAsc.size()));

	    
	    // === Create set of all matrix column indices due to the periodic ===
	    // === associations of the column DOF index.                       ===

	    vector<int> newCols;
608
	    perMap.mapDof(colFe, globalColDof, perAsc, newCols);
Thomas Witkowski's avatar
Thomas Witkowski committed
609
	    for (unsigned int i = 0; i < newCols.size(); i++) {
610
	      cols.push_back(interiorMap->getMatIndex(nColMat, newCols[i]));
Thomas Witkowski's avatar
Thomas Witkowski committed
611
612
613
614
615
	      values.push_back(scaledValue);	      
	    }
	  }
	}

616
  	MatSetValues(petscData.getInteriorMat(), 1, &rowIndex, cols.size(), 
Thomas Witkowski's avatar
Thomas Witkowski committed
617
  		     &(cols[0]), &(values[0]), ADD_VALUES);	
Thomas Witkowski's avatar
Thomas Witkowski committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
      } else {
	// === Row DOF index is periodic. ===

	// Because this row is periodic, we will have to add the entries of this 
	// matrix row to multiple rows. The following maps store to each row an
	// array of column indices and values of the entries that must be added to
	// the PETSc matrix.
	map<int, vector<int> > colsMap;
	map<int, vector<double> > valsMap;

	// Traverse all column entries.
	for (icursor_type icursor = begin<nz>(cursor), icend = end<nz>(cursor); 
	     icursor != icend; ++icursor) {
	  // Global index of the current column index.
632
	  int globalColDof = (*interiorMap)[colFe][col(*icursor)].global;
Thomas Witkowski's avatar
Thomas Witkowski committed
633
634
635
636
637
638
639
640
641

	  // Ignore all zero entries, expect it is a diagonal entry.
 	  if (value(*icursor) == 0.0 && globalRowDof != globalColDof)
 	    continue;

	  // === Add all periodic associations of both, the row and the column ===
	  // === indices to the set perAsc.                                    ===

	  std::set<int> perAsc;
642
643
644
645
	  perMap.fillAssociations(colFe, globalColDof, 
				  meshDistributor->getElementObjectDb(), perAsc);
	  perMap.fillAssociations(rowFe, globalRowDof, 
				  meshDistributor->getElementObjectDb(), perAsc);
Thomas Witkowski's avatar
Thomas Witkowski committed
646
647
648
649
650
651
652
653
654
655

	  // Scale the value with respect to the number of periodic associations.
	  double scaledValue = 
	    value(*icursor) * pow(0.5, static_cast<double>(perAsc.size()));


	  // === Create all matrix entries with respect to the periodic  ===
	  // === associations of the row and column indices.             ===

	  vector<pair<int, int> > entry;
Thomas Witkowski's avatar
Blbu  
Thomas Witkowski committed
656
657
	  perMap.mapDof(rowFe, colFe, make_pair(globalRowDof, globalColDof),
			perAsc, entry);
Thomas Witkowski's avatar
Thomas Witkowski committed
658
659
660

	  // === Translate the matrix entries to PETSc's matrix.

661
	  for (unsigned int i = 0; i < entry.size(); i++) {
662
663
	    int rowIdx = interiorMap->getMatIndex(nRowMat, entry[i].first);
	    int colIdx = interiorMap->getMatIndex(nColMat, entry[i].second);
Thomas Witkowski's avatar
Thomas Witkowski committed
664

665
666
	    colsMap[rowIdx].push_back(colIdx);
	    valsMap[rowIdx].push_back(scaledValue);
Thomas Witkowski's avatar
Thomas Witkowski committed
667
668
669
670
671
672
673
674
675
676
677
678
	  }
	}


	// === Finally, add all periodic rows to the PETSc matrix. ===

	for (map<int, vector<int> >::iterator rowIt = colsMap.begin();
	     rowIt != colsMap.end(); ++rowIt) {
	  TEST_EXIT_DBG(rowIt->second.size() == valsMap[rowIt->first].size())
	    ("Should not happen!\n");

	  int rowIndex = rowIt->first;
679

680
	  MatSetValues(petscData.getInteriorMat(), 1, &rowIndex, rowIt->second.size(),
Thomas Witkowski's avatar
Thomas Witkowski committed
681
682
683
684
685
686
687
		       &(rowIt->second[0]), &(valsMap[rowIt->first][0]), ADD_VALUES);
	}
      }
    }
  }


Thomas Witkowski's avatar
Thomas Witkowski committed
688
689
  void PetscSolverGlobalMatrix::setDofVector(Vec vecInterior, 
					     Vec vecCoarse,
690
					     DOFVector<double>* vec, 
691
					     int nRowVec, 
692
					     bool rankOnly)
Thomas Witkowski's avatar
Thomas Witkowski committed
693
694
695
  {
    FUNCNAME("PetscSolverGlobalMatrix::setDofVector()");

696
    const FiniteElemSpace *feSpace = vec->getFeSpace();
697
    PeriodicMap &perMap = meshDistributor->getPeriodicMap();
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
698
699
    int rStartInterior = petscData.getStartInterior();

Thomas Witkowski's avatar
Thomas Witkowski committed
700
701
702
    ParallelDofMapping *rowCoarseSpace = NULL;
    if (coarseSpaceMap.size())
      rowCoarseSpace = coarseSpaceMap[nRowVec];
703

Thomas Witkowski's avatar
Thomas Witkowski committed
704
705
706
    // Traverse all used DOFs in the dof vector.
    DOFVector<double>::Iterator dofIt(vec, USED_DOFS);
    for (dofIt.reset(); !dofIt.end(); ++dofIt) {
707

708
      if (rankOnly && !(*interiorMap)[feSpace].isRankDof(dofIt.getDOFIndex()))
Thomas Witkowski's avatar
Thomas Witkowski committed
709
710
	continue;

Thomas Witkowski's avatar
Thomas Witkowski committed
711
      if (isCoarseSpace(nRowVec, feSpace, dofIt.getDOFIndex())) {
712
713
	TEST_EXIT_DBG(vecCoarse != PETSC_NULL)("Should not happen!\n");

Thomas Witkowski's avatar
Thomas Witkowski committed
714
	int index = rowCoarseSpace->getMatIndex(nRowVec, dofIt.getDOFIndex());
715
716
717
718
719
720
721
722
723
724
725
726
727
728
	VecSetValue(vecCoarse, index, *dofIt, ADD_VALUES);
      } else {
	// Calculate global row index of the DOF.
	DegreeOfFreedom globalRowDof = 
	  (*interiorMap)[feSpace][dofIt.getDOFIndex()].global;
	
	// Get PETSc's mat index of the row DOF.
	int index = 0;
	if (interiorMap->isMatIndexFromGlobal())
	  index = 
	    interiorMap->getMatIndex(nRowVec, globalRowDof) + rStartInterior;
	else
	  index =
	    interiorMap->getMatIndex(nRowVec, dofIt.getDOFIndex()) + rStartInterior;
729

730
	if (perMap.isPeriodic(feSpace, globalRowDof)) {
Thomas Witkowski's avatar
Thomas Witkowski committed
731
732
733
	  std::set<int>& perAsc = perMap.getAssociations(feSpace, globalRowDof);
	  double value = *dofIt / (perAsc.size() + 1.0);
	  VecSetValue(vecInterior, index, value, ADD_VALUES);
734

Thomas Witkowski's avatar
Thomas Witkowski committed
735
736
737
738
	  for (std::set<int>::iterator perIt = perAsc.begin(); 
	       perIt != perAsc.end(); ++perIt) {
	    int mappedDof = perMap.map(feSpace, *perIt, globalRowDof);
	    int mappedIndex = interiorMap->getMatIndex(nRowVec, mappedDof);
739

Thomas Witkowski's avatar
Thomas Witkowski committed
740
	    VecSetValue(vecInterior, mappedIndex, value, ADD_VALUES);
741
742
743
744
	  }	  
	} else {	  
	  // The DOF index is not periodic.
	  
Thomas Witkowski's avatar
Thomas Witkowski committed
745
746
	  VecSetValue(vecInterior, index, *dofIt, ADD_VALUES);
	}
Thomas Witkowski's avatar
Thomas Witkowski committed
747
748
749
750
751
      }
    }
  }


752
753
  void PetscSolverGlobalMatrix::removeDirichletBcDofs(Matrix<DOFMatrix*> *mat)
  {
Thomas Witkowski's avatar
Thomas Witkowski committed
754
    FUNCNAME("PetscSolverGlobalMatrix::removeDirichletBcDofs()");    
755
756
757
758
759
760
  }


  void PetscSolverGlobalMatrix::removeDirichletBcDofs(SystemVector *vec)
  {
    FUNCNAME("PetscSolverGlobalMatrix::removeDirichletBcDofs()");
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
761
  } 
762

Thomas Witkowski's avatar
Thomas Witkowski committed
763
}