PetscSolverGlobalMatrix.cc 23.7 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
    createMatVec(*seqMat);
31

Thomas Witkowski's avatar
Thomas Witkowski committed
32
    if (coarseSpaceMap.size()) {
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
33
      fillPetscMatrixWithCoarseSpace(seqMat);
34 35 36
      return;
    }

37 38
    // === Create PETSc vector (solution and a temporary vector). ===

Thomas Witkowski's avatar
Thomas Witkowski committed
39 40 41 42 43 44
#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
45
    int nComponents = seqMat->getNumRows();
Thomas Witkowski's avatar
Thomas Witkowski committed
46 47
    for (int i = 0; i < nComponents; i++)
      for (int j = 0; j < nComponents; j++)
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
48 49
	if ((*seqMat)[i][j])
	  setDofMatrix((*seqMat)[i][j], i, j);
Thomas Witkowski's avatar
Thomas Witkowski committed
50 51 52 53 54

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

55
    matAssembly();
56 57 58
    
    if (printMatInfo) {
      MatInfo matInfo;
59
      MatGetInfo(getMatInterior(), MAT_GLOBAL_SUM, &matInfo);
60 61 62 63 64 65 66
      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));
    }
67

68
    // === Init PETSc solver. ===
69

70 71
    KSPCreate(mpiCommGlobal, &kspInterior);
    KSPGetPC(kspInterior, &pcInterior);
72
    KSPSetOperators(kspInterior, getMatInterior(), getMatInterior(), 
73
		    SAME_NONZERO_PATTERN); 
74 75 76 77
    KSPSetTolerances(kspInterior, 0.0, 1e-8, PETSC_DEFAULT, PETSC_DEFAULT);
    KSPSetType(kspInterior, KSPBCGS);
    KSPSetOptionsPrefix(kspInterior, kspPrefix.c_str());
    KSPSetFromOptions(kspInterior);
78

79
    initPreconditioner(pcInterior);
80

81 82
    // Do not delete the solution vector, use it for the initial guess.
    if (!zeroStartVector)
83
      KSPSetInitialGuessNonzero(kspInterior, PETSC_TRUE);
84

Thomas Witkowski's avatar
Thomas Witkowski committed
85 86 87
#if (DEBUG != 0)
    MSG("Fill petsc matrix 3 needed %.5f seconds\n", MPI::Wtime() - wtime);
#endif
88 89 90
  }


91 92 93 94 95 96 97 98
  void PetscSolverGlobalMatrix::fillPetscMatrix(DOFMatrix *mat)
  {
    Matrix<DOFMatrix*> m(1, 1);
    m[0][0] = mat;
    fillPetscMatrix(&m);
  }


Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
99
  void PetscSolverGlobalMatrix::fillPetscMatrixWithCoarseSpace(Matrix<DOFMatrix*> *seqMat)
100 101
  {
    FUNCNAME("PetscSolverGlobalMatrix::fillPetscMatrixWithCoarseSpace()");
102 103

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

107
    vector<const FiniteElemSpace*> feSpaces = AMDiS::getComponentFeSpaces(*seqMat);
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
108

109 110
    int nRowsRankInterior = interiorMap->getRankDofs();
    int nRowsOverallInterior = interiorMap->getOverallDofs();
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    // === 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
131
    int nComponents = seqMat->getSize();
Thomas Witkowski's avatar
Thomas Witkowski committed
132 133 134 135 136
    for (int rowComponent = 0; rowComponent < nComponents; rowComponent++) {
      for (int colComponent = 0; colComponent < nComponents; colComponent++) {
	DOFMatrix* dofMat = (*seqMat)[rowComponent][colComponent];

	if (!dofMat)
137 138
	  continue;

Thomas Witkowski's avatar
Thomas Witkowski committed
139 140
	MSG("=============== COMP %d %d ================= \n", rowComponent, colComponent);

Thomas Witkowski's avatar
Thomas Witkowski committed
141 142
	ParallelDofMapping *rowCoarseSpace = coarseSpaceMap[rowComponent];
	ParallelDofMapping *colCoarseSpace = coarseSpaceMap[colComponent];
Thomas Witkowski's avatar
Thomas Witkowski committed
143

Thomas Witkowski's avatar
Thomas Witkowski committed
144 145
	traits::col<Matrix>::type col(dofMat->getBaseMatrix());
	traits::const_value<Matrix>::type value(dofMat->getBaseMatrix());
146 147
	
	// Traverse all rows.
Thomas Witkowski's avatar
Thomas Witkowski committed
148 149
	for (cursor_type cursor = begin<row>(dofMat->getBaseMatrix()), 
	       cend = end<row>(dofMat->getBaseMatrix()); cursor != cend; ++cursor) {
150

Thomas Witkowski's avatar
Thomas Witkowski committed
151
	  bool isRowCoarse = 
Thomas Witkowski's avatar
Thomas Witkowski committed
152
	    isCoarseSpace(rowComponent, feSpaces[rowComponent], *cursor);
153 154 155 156 157 158 159 160 161 162
  
	  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
163 164
	    bool isColCoarse = 
	      isCoarseSpace(colComponent, feSpaces[colComponent], col(*icursor));
165

Thomas Witkowski's avatar
Thomas Witkowski committed
166 167 168 169
	    if (colComponent == 2 && col(*icursor) == 19) {
	      MSG("HERE WE TEST: %d %d\n", isColCoarse, isRowCoarse);
	    }

Thomas Witkowski's avatar
Thomas Witkowski committed
170 171
	    if (isColCoarse) {
	      if (isRowCoarse) {
172 173 174 175 176 177 178
		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
179
	      if (isRowCoarse) {
180 181 182 183 184 185 186 187 188 189 190 191
		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
192
	  if (isRowCoarse) {
Thomas Witkowski's avatar
Thomas Witkowski committed
193
	    MSG("A-GET MAT INDEX %d\n", rowComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
194
	    int rowIndex = rowCoarseSpace->getMatIndex(rowComponent, *cursor);
Thomas Witkowski's avatar
Thomas Witkowski committed
195
	    MSG("B-GET MAT INDEX %d\n", colComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
196 197
	    for (unsigned int i = 0; i < cols.size(); i++)
	      cols[i] = colCoarseSpace->getMatIndex(colComponent, cols[i]);
198

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
199
	    // matCoarseCoarse
Thomas Witkowski's avatar
Thomas Witkowski committed
200 201
	    //MSG("SET COARSE MAT COMP %d %d WITH %d entry\n", rowComponent, colComponent, cols.size());
	    MatSetValues(getMatCoarseByComponent(rowComponent, colComponent),
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
202
			 1, &rowIndex, cols.size(),
203 204 205 206
			 &(cols[0]), &(values[0]), ADD_VALUES);

	    if (colsOther.size()) {
	      if (subdomainLevel == 0) {
Thomas Witkowski's avatar
Thomas Witkowski committed
207
		MSG("C0-GET MAT INDEX %d\n", colComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
208 209 210
		for (unsigned int i = 0; i < colsOther.size(); i++)
		  colsOther[i] = 
		    interiorMap->getMatIndex(colComponent, colsOther[i]);
211
	      } else {
Thomas Witkowski's avatar
Thomas Witkowski committed
212
		MSG("C1-GET MAT INDEX %d\n", colComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
213 214 215 216
		for (unsigned int i = 0; i < colsOther.size(); i++)
		  colsOther[i] = 
		    interiorMap->getMatIndex(colComponent, colsOther[i]) + 
		    rStartInterior;
217
	      }
218

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
219
	      // matCoarseInt
Thomas Witkowski's avatar
Thomas Witkowski committed
220
	      //    MSG("SET COARSE-INT MAT COMP %d %d WITH %d entry\n", rowComponent, colComponent, cols.size());
Thomas Witkowski's avatar
Thomas Witkowski committed
221
	      MatSetValues(getMatCoarseInteriorByComponent(rowComponent), 
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
222
			   1, &rowIndex, colsOther.size(),
223 224 225
 			   &(colsOther[0]), &(valuesOther[0]), ADD_VALUES);
	    }
	  } else {
Thomas Witkowski's avatar
Thomas Witkowski committed
226
	    MSG("D-GET MAT INDEX %d\n", rowComponent);
227
	    int localRowIndex = 
Thomas Witkowski's avatar
Thomas Witkowski committed
228 229 230
	      (subdomainLevel == 0 ? 
	       interiorMap->getLocalMatIndex(rowComponent, *cursor) :
	       interiorMap->getMatIndex(rowComponent, *cursor));
231

Thomas Witkowski's avatar
Thomas Witkowski committed
232
	    MSG("E-GET MAT INDEX %d\n", colComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
233
	    for (unsigned int i = 0; i < cols.size(); i++) {
234
	      if (subdomainLevel == 0)
Thomas Witkowski's avatar
Thomas Witkowski committed
235
		cols[i] = interiorMap->getLocalMatIndex(colComponent, cols[i]);
236
	      else
Thomas Witkowski's avatar
Thomas Witkowski committed
237
		cols[i] = interiorMap->getMatIndex(colComponent, cols[i]);
238
	    }
Thomas Witkowski's avatar
Thomas Witkowski committed
239
	    MSG("DONE\n");
240
	    
241
  	    MatSetValues(getMatInterior(), 1, &localRowIndex, cols.size(),
242
  			 &(cols[0]), &(values[0]), ADD_VALUES);
Thomas Witkowski's avatar
Thomas Witkowski committed
243
	    
244
	    if (colsOther.size()) {
Thomas Witkowski's avatar
Thomas Witkowski committed
245
	      MSG("F-GET MAT INDEX %d\n", colComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
246
	      int globalRowIndex = interiorMap->getMatIndex(rowComponent, *cursor);
247 248 249

	      if (subdomainLevel != 0)
		globalRowIndex += rStartInterior;
Thomas Witkowski's avatar
Thomas Witkowski committed
250 251
	      
	      MSG("G-GET MAT INDEX %d\n", colComponent);
Thomas Witkowski's avatar
Thomas Witkowski committed
252 253 254
	      for (unsigned int i = 0; i < colsOther.size(); i++)
		colsOther[i] = 
		  colCoarseSpace->getMatIndex(colComponent, colsOther[i]);
255

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
256
	      // matIntCoarse
Thomas Witkowski's avatar
Thomas Witkowski committed
257 258
	      //	      MSG("SET INT-COARSE MAT COMP %d %d WITH %d entry\n", rowComponent, colComponent, cols.size());
  	      MatSetValues(getMatInteriorCoarseByComponent(colComponent), 
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
259
			   1, &globalRowIndex, colsOther.size(),
260 261 262 263 264 265 266
  			   &(colsOther[0]), &(valuesOther[0]), ADD_VALUES);
	    }
	  }
	} 
      }
    }

267
    matAssembly();
268

269 270 271
    // === Create solver for the non primal (thus local) variables. ===

    KSPCreate(mpiCommLocal, &kspInterior);
272
    KSPSetOperators(kspInterior, getMatInterior(), getMatInterior(),
273
		    SAME_NONZERO_PATTERN);
274 275 276 277 278 279 280 281 282 283 284 285
    KSPSetOptionsPrefix(kspInterior, "interior_");
    KSPSetType(kspInterior, KSPPREONLY);
    KSPGetPC(kspInterior, &pcInterior);
    PCSetType(pcInterior, PCLU);
    if (subdomainLevel == 0)
      PCFactorSetMatSolverPackage(pcInterior, MATSOLVERUMFPACK);
    else
      PCFactorSetMatSolverPackage(pcInterior, MATSOLVERMUMPS);
    KSPSetFromOptions(kspInterior);  
  }


286 287 288
  void PetscSolverGlobalMatrix::fillPetscRhs(SystemVector *vec)
  {
    FUNCNAME("PetscSolverGlobalMatrix::fillPetscRhs()");
Thomas Witkowski's avatar
Thomas Witkowski committed
289

290
    TEST_EXIT_DBG(vec)("No DOF vector defined!\n");
291
    TEST_EXIT_DBG(interiorMap)("No parallel DOF map defined!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
292
    
Thomas Witkowski's avatar
Thomas Witkowski committed
293
    // === Transfer values from DOF vector to the PETSc vector. === 
Thomas Witkowski's avatar
Thomas Witkowski committed
294
    if (coarseSpaceMap.size()) {
Thomas Witkowski's avatar
Thomas Witkowski committed
295
      for (int i = 0; i < vec->getSize(); i++)
296
	setDofVector(getVecRhsInterior(), getVecRhsCoarse(), vec->getDOFVector(i), i);
Thomas Witkowski's avatar
Thomas Witkowski committed
297 298
    } else {
      for (int i = 0; i < vec->getSize(); i++)
299
	setDofVector(getVecRhsInterior(), vec->getDOFVector(i), i);
Thomas Witkowski's avatar
Thomas Witkowski committed
300 301
    }

302
    vecRhsAssembly();
Thomas Witkowski's avatar
Thomas Witkowski committed
303 304 305
  }


306 307
  void PetscSolverGlobalMatrix::solvePetscMatrix(SystemVector &vec, 
						 AdaptInfo *adaptInfo)
Thomas Witkowski's avatar
Thomas Witkowski committed
308 309 310 311 312 313 314
  {
    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
315 316
      TEST_EXIT(coarseSpaceMap.size() == 0)("Not yet supported!\n");

317
      VecSet(getVecSolInterior(), 0.0);
Thomas Witkowski's avatar
Thomas Witkowski committed
318 319
      
      for (int i = 0; i < nComponents; i++)
320
	setDofVector(getVecSolInterior(), vec.getDOFVector(i), i, true);
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
321

322
      vecSolAssembly();
Thomas Witkowski's avatar
Thomas Witkowski committed
323 324
    }

325

Thomas Witkowski's avatar
Thomas Witkowski committed
326 327
    MatNullSpace matNullspace;
    Vec nullspaceBasis;
328 329 330
    if (nullspace.size() > 0 || 
	hasConstantNullspace ||
	constNullspaceComponent.size() > 0) {
Thomas Witkowski's avatar
Thomas Witkowski committed
331
      TEST_EXIT_DBG(nullspace.size() <= 1)("Not yet implemented!\n");
332

333 334 335 336 337 338 339 340 341 342
      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
343
      if (nullspace.size() > 0) {
344
	VecDuplicate(getVecSolInterior(), &nullspaceBasis);
Thomas Witkowski's avatar
Thomas Witkowski committed
345 346 347 348 349
	for (int i = 0; i < nComponents; i++)
	  setDofVector(nullspaceBasis, nullspace[0]->getDOFVector(i), i, true);
	
	VecAssemblyBegin(nullspaceBasis);
	VecAssemblyEnd(nullspaceBasis);
350 351

	VecNormalize(nullspaceBasis, PETSC_NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
352 353 354 355
	
	MatNullSpaceCreate(mpiCommGlobal, (hasConstantNullspace ? PETSC_TRUE : PETSC_FALSE), 
			   1, &nullspaceBasis, &matNullspace);

356
	MatMult(getMatInterior(), nullspaceBasis, getVecSolInterior());
Thomas Witkowski's avatar
Thomas Witkowski committed
357
	PetscReal n;
358
	VecNorm(getVecSolInterior(), NORM_2, &n);
Thomas Witkowski's avatar
Thomas Witkowski committed
359 360 361 362
	MSG("NORM IS: %e\n", n);
      } else {
	MatNullSpaceCreate(mpiCommGlobal, PETSC_TRUE, 0, PETSC_NULL, &matNullspace);
      }
363

364
      MatSetNullSpace(getMatInterior(), matNullspace);
Thomas Witkowski's avatar
Thomas Witkowski committed
365
      KSPSetNullSpace(kspInterior, matNullspace);
366

Thomas Witkowski's avatar
Thomas Witkowski committed
367
      // === Remove null space, if requested. ===
368

Thomas Witkowski's avatar
Thomas Witkowski committed
369
      if (removeRhsNullspace) {
Thomas Witkowski's avatar
Thomas Witkowski committed
370
	TEST_EXIT_DBG(coarseSpaceMap.empty())("Not supported!\n");
371 372

	MSG("Remove nullspace from rhs vector.\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
373
	
374
	MatNullSpaceRemove(matNullspace, getVecRhsInterior(), PETSC_NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
375 376 377 378
      }
    } else {
      TEST_EXIT(removeRhsNullspace == false)
	("No nullspace provided that should be removed from rhs!\n");
379 380
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
381
    // PETSc.
382
    solve(getVecRhsInterior(), getVecSolInterior());
Thomas Witkowski's avatar
Thomas Witkowski committed
383

384 385

    if (nullspace.size() > 0) {
Thomas Witkowski's avatar
Thomas Witkowski committed
386
      MatNullSpaceDestroy(&matNullspace);
387 388 389 390
      VecDestroy(&nullspaceBasis);
    }


Thomas Witkowski's avatar
Thomas Witkowski committed
391 392
    // === Transfere values from PETSc's solution vectors to the DOF vectors. ===
    PetscScalar *vecPointer;
393
    VecGetArray(getVecSolInterior(), &vecPointer);    
Thomas Witkowski's avatar
Thomas Witkowski committed
394

395
    int c = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
396
    for (int i = 0; i < nComponents; i++) {
397
      DOFVector<double> &dv = *(vec.getDOFVector(i));
398

399
      DofMap& d = (*interiorMap)[dv.getFeSpace()].getMap();
400 401 402
      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
403 404
    }

405
    VecRestoreArray(getVecSolInterior(), &vecPointer);
Thomas Witkowski's avatar
Thomas Witkowski committed
406 407 408 409

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


413 414 415 416
  void PetscSolverGlobalMatrix::solveGlobal(Vec &rhs, Vec &sol)
  {
    FUNCNAME("PetscSolverGlobalMatrix::solveGlobal()");

417 418 419
    double wtime = MPI::Wtime();
    double t0 = 0.0, t1 = 0.0;

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    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);

439 440 441
    t0 = MPI::Wtime() - wtime;

    wtime = MPI::Wtime();
442
    KSPSolve(kspInterior, tmp, tmp);
443 444 445
    t1 = MPI::Wtime() - wtime;

    wtime = MPI::Wtime();
446 447 448 449 450 451 452 453 454 455 456

    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);
457 458
    t0 += MPI::Wtime() - wtime;

459
    //    MSG("TIMEING: %.5f %.5f\n", t0, t1);
460 461 462
  }


463 464 465 466
  void PetscSolverGlobalMatrix::destroyMatrixData()
  {
    FUNCNAME("PetscSolverGlobalMatrix::destroyMatrixData()");

467 468
    exitPreconditioner(pcInterior);

469
    matDestroy();
Thomas Witkowski's avatar
Thomas Witkowski committed
470

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
471
    KSPDestroy(&kspInterior);
Thomas Witkowski's avatar
Thomas Witkowski committed
472 473 474
  }


475 476 477 478
  void PetscSolverGlobalMatrix::destroyVectorData()
  {
    FUNCNAME("PetscSolverGlobalMatrix::destroyVectorData()");

479
    vecDestroy();
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 506 507 508 509 510 511 512 513 514 515 516 517 518
  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);
    }
  }


519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
  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
534
  void PetscSolverGlobalMatrix::setDofMatrix(DOFMatrix* seqMat,
535
					     int nRowMat, int nColMat)
Thomas Witkowski's avatar
Thomas Witkowski committed
536 537 538
  {
    FUNCNAME("PetscSolverGlobalMatrix::setDofMatrix()");

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
539
    TEST_EXIT(seqMat)("No DOFMatrix!\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
540 541

    using mtl::tag::row; using mtl::tag::nz; using mtl::begin; using mtl::end;
542
    namespace traits = mtl::traits;
Thomas Witkowski's avatar
Thomas Witkowski committed
543 544
    typedef DOFMatrix::base_matrix_type Matrix;

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
545 546
    traits::col<Matrix>::type col(seqMat->getBaseMatrix());
    traits::const_value<Matrix>::type value(seqMat->getBaseMatrix());
Thomas Witkowski's avatar
Thomas Witkowski committed
547 548 549 550 551 552 553 554 555 556 557

    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;

558 559 560
    // Get periodic mapping object
    PeriodicMap &perMap = meshDistributor->getPeriodicMap();

Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
561 562
    const FiniteElemSpace *rowFe = seqMat->getRowFeSpace();
    const FiniteElemSpace *colFe = seqMat->getColFeSpace();
Thomas Witkowski's avatar
Thomas Witkowski committed
563 564 565 566
    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
567 568
    // === to the PETSc matrix.                                               ===

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

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

Thomas Witkowski's avatar
Thomas Witkowski committed
577 578 579
      if (!periodicRow) {
	// === Row DOF index is not periodic. ===

580
	// Get PETSc's mat row index.
581
	int rowIndex = interiorMap->getMatIndex(nRowMat, globalRowDof);
Thomas Witkowski's avatar
Thomas Witkowski committed
582 583 584 585 586 587 588 589

	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
590
	  int globalColDof = colMap[col(*icursor)].global;
Thomas Witkowski's avatar
Thomas Witkowski committed
591
	  // Test if the current col dof is a periodic dof.
592
	  bool periodicCol = perMap.isPeriodic(colFe, globalColDof);
593
	  // Get PETSc's mat col index.
594
	  int colIndex = interiorMap->getMatIndex(nColMat, globalColDof);
Thomas Witkowski's avatar
Thomas Witkowski committed
595 596 597 598 599 600 601

	  // 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
602 603
 	    cols.push_back(colIndex);
 	    values.push_back(value(*icursor));
Thomas Witkowski's avatar
Thomas Witkowski committed
604 605 606 607 608
	  } else {
	    // === Row index is not periodic, but column index is. ===

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

Thomas Witkowski's avatar
Thomas Witkowski committed
612 613 614 615 616 617 618 619 620
	    // 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;
621
	    perMap.mapDof(colFe, globalColDof, perAsc, newCols);
Thomas Witkowski's avatar
Thomas Witkowski committed
622
	    for (unsigned int i = 0; i < newCols.size(); i++) {
623
	      cols.push_back(interiorMap->getMatIndex(nColMat, newCols[i]));
Thomas Witkowski's avatar
Thomas Witkowski committed
624 625 626 627 628
	      values.push_back(scaledValue);	      
	    }
	  }
	}

629
  	MatSetValues(getMatInterior(), 1, &rowIndex, cols.size(), 
Thomas Witkowski's avatar
Thomas Witkowski committed
630
  		     &(cols[0]), &(values[0]), ADD_VALUES);	
Thomas Witkowski's avatar
Thomas Witkowski committed
631 632 633 634 635 636 637 638 639 640 641 642 643 644
      } 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.
645
	  int globalColDof = (*interiorMap)[colFe][col(*icursor)].global;
Thomas Witkowski's avatar
Thomas Witkowski committed
646 647 648 649 650 651 652 653 654

	  // 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;
655 656 657 658
	  perMap.fillAssociations(colFe, globalColDof, 
				  meshDistributor->getElementObjectDb(), perAsc);
	  perMap.fillAssociations(rowFe, globalRowDof, 
				  meshDistributor->getElementObjectDb(), perAsc);
Thomas Witkowski's avatar
Thomas Witkowski committed
659 660 661 662 663 664 665 666 667 668

	  // 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
669 670
	  perMap.mapDof(rowFe, colFe, make_pair(globalRowDof, globalColDof),
			perAsc, entry);
Thomas Witkowski's avatar
Thomas Witkowski committed
671 672 673

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

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

678 679
	    colsMap[rowIdx].push_back(colIdx);
	    valsMap[rowIdx].push_back(scaledValue);
Thomas Witkowski's avatar
Thomas Witkowski committed
680 681 682 683 684 685 686 687 688 689 690 691
	  }
	}


	// === 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;
692

693
	  MatSetValues(getMatInterior(), 1, &rowIndex, rowIt->second.size(),
Thomas Witkowski's avatar
Thomas Witkowski committed
694 695 696 697 698 699 700
		       &(rowIt->second[0]), &(valsMap[rowIt->first][0]), ADD_VALUES);
	}
      }
    }
  }


Thomas Witkowski's avatar
Thomas Witkowski committed
701 702
  void PetscSolverGlobalMatrix::setDofVector(Vec vecInterior, 
					     Vec vecCoarse,
703
					     DOFVector<double>* vec, 
704
					     int nRowVec, 
705
					     bool rankOnly)
Thomas Witkowski's avatar
Thomas Witkowski committed
706 707 708
  {
    FUNCNAME("PetscSolverGlobalMatrix::setDofVector()");

709
    const FiniteElemSpace *feSpace = vec->getFeSpace();
710
    PeriodicMap &perMap = meshDistributor->getPeriodicMap();
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
711

Thomas Witkowski's avatar
Thomas Witkowski committed
712 713 714
    ParallelDofMapping *rowCoarseSpace = NULL;
    if (coarseSpaceMap.size())
      rowCoarseSpace = coarseSpaceMap[nRowVec];
715

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

720
      if (rankOnly && !(*interiorMap)[feSpace].isRankDof(dofIt.getDOFIndex()))
Thomas Witkowski's avatar
Thomas Witkowski committed
721 722
	continue;

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

Thomas Witkowski's avatar
Thomas Witkowski committed
726
	int index = rowCoarseSpace->getMatIndex(nRowVec, dofIt.getDOFIndex());
727 728 729 730 731 732 733 734 735 736 737 738 739 740
	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;
741

742
	if (perMap.isPeriodic(feSpace, globalRowDof)) {
Thomas Witkowski's avatar
Thomas Witkowski committed
743 744 745
	  std::set<int>& perAsc = perMap.getAssociations(feSpace, globalRowDof);
	  double value = *dofIt / (perAsc.size() + 1.0);
	  VecSetValue(vecInterior, index, value, ADD_VALUES);
746

Thomas Witkowski's avatar
Thomas Witkowski committed
747 748 749 750
	  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);
751

Thomas Witkowski's avatar
Thomas Witkowski committed
752
	    VecSetValue(vecInterior, mappedIndex, value, ADD_VALUES);
753 754 755 756
	  }	  
	} else {	  
	  // The DOF index is not periodic.
	  
Thomas Witkowski's avatar
Thomas Witkowski committed
757 758
	  VecSetValue(vecInterior, index, *dofIt, ADD_VALUES);
	}
Thomas Witkowski's avatar
Thomas Witkowski committed
759 760 761 762 763
      }
    }
  }

}