ProblemVec.cc 41.9 KB
Newer Older
Thomas Witkowski's avatar
Thomas Witkowski committed
1
#include <sstream>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "ProblemVec.h"
#include "RecoveryEstimator.h"
#include "Serializer.h"
#include "AbstractFunction.h"
#include "Operator.h"
#include "SystemVector.h"
#include "DOFMatrix.h"
#include "FiniteElemSpace.h"
#include "Estimator.h"
#include "Marker.h"
#include "AdaptInfo.h"
#include "FileWriter.h"
#include "CoarseningManager.h"
#include "RefinementManager.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
16
#include "DualTraverse.h"
17
18
19
20
21
22
#include "Mesh.h"
#include "OEMSolver.h"
#include "DirichletBC.h"
#include "RobinBC.h"
#include "PeriodicBC.h"
#include "Lagrange.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
23
#include "Flag.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
24
#include "TraverseParallel.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
25
#include "VtkWriter.h"
26
#include "ValueReader.h"
27
28
29
30
31
32
33
34
35
36

namespace AMDiS {

  void ProblemVec::initialize(Flag initFlag,
			      ProblemVec *adoptProblem,
			      Flag adoptFlag)
  {
    FUNCNAME("ProblemVec::initialize()");
    
    // === create meshes ===
Thomas Witkowski's avatar
Thomas Witkowski committed
37
    if (meshes.size() != 0) { 
38
39
40
41
42
43
44
45
46
47
48
      WARNING("meshes already created\n");
    } else {
      if (initFlag.isSet(CREATE_MESH) || 
	  ((!adoptFlag.isSet(INIT_MESH))&&
	   (initFlag.isSet(INIT_SYSTEM) || initFlag.isSet(INIT_FE_SPACE)))) {
	createMesh();
      } 
      if (adoptProblem && 
	  (adoptFlag.isSet(INIT_MESH) || 
	   adoptFlag.isSet(INIT_SYSTEM) ||
	   adoptFlag.isSet(INIT_FE_SPACE))) {
Thomas Witkowski's avatar
Thomas Witkowski committed
49
	meshes = adoptProblem->getMeshes();
Thomas Witkowski's avatar
Thomas Witkowski committed
50
	componentMeshes = adoptProblem->componentMeshes;
Thomas Witkowski's avatar
Thomas Witkowski committed
51
52
	refinementManager = adoptProblem->refinementManager;
	coarseningManager = adoptProblem->coarseningManager;
53
54
55

	// If the adopt problem has fewer components than this problem, but only one
	// mesh for all component, than scal up the componentMeshes array.
Thomas Witkowski's avatar
Thomas Witkowski committed
56
	if (adoptProblem->getNumComponents() < nComponents) {
Thomas Witkowski's avatar
Thomas Witkowski committed
57
	  TEST_EXIT(meshes.size() == 1)("Daran muss ich noch arbeiten!\n");
58
	  
Thomas Witkowski's avatar
Thomas Witkowski committed
59
	  componentMeshes.resize(nComponents);
60
	  for (int i = adoptProblem->getNumComponents(); i < nComponents; i++)
Thomas Witkowski's avatar
Thomas Witkowski committed
61
	    componentMeshes[i] = componentMeshes[0];
62
63
	}

64
65
66
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
67
    if (meshes.size() == 0) 
68
69
70
      WARNING("no mesh created\n");

    // === create fespace ===
71
    if (feSpaces.size() != 0) {
72
73
74
75
76
77
78
79
      WARNING("feSpaces already created\n");
    } else {
      if (initFlag.isSet(INIT_FE_SPACE) || 
	  (initFlag.isSet(INIT_SYSTEM)&&!adoptFlag.isSet(INIT_FE_SPACE))) {
	createFESpace();
      } 
      if (adoptProblem &&
	  (adoptFlag.isSet(INIT_FE_SPACE) || adoptFlag.isSet(INIT_SYSTEM))) {
80
81
	feSpaces = adoptProblem->getFESpaces();
	componentSpaces = adoptProblem->componentSpaces;
Thomas Witkowski's avatar
Thomas Witkowski committed
82
	traverseInfo = adoptProblem->traverseInfo;
83
84
85

	// If the adopt problem has fewer components than this problem, but only one
	// fe space for all component, than scal up the componentSpaces array.
Thomas Witkowski's avatar
Thomas Witkowski committed
86
87
	if (adoptProblem->getNumComponents() < nComponents) {
	  TEST_EXIT(feSpaces.size() == 1)("Daran muss ich noch arbeiten!\n");
88
	  
Thomas Witkowski's avatar
Thomas Witkowski committed
89
90
91
	  componentSpaces.resize(nComponents);
	  for (int i = adoptProblem->getNumComponents(); i < nComponents; i++) {
	    componentSpaces[i] = componentSpaces[0];
92
93
94
	  }
	}

95
96
97
      }
    }

98
    if (feSpaces.size() == 0) 
99
100
101
102
103
104
105
      WARNING("no feSpace created\n");

    // === create system ===
    if (initFlag.isSet(INIT_SYSTEM)) {
      createMatricesAndVectors();
    } 
    if (adoptProblem && adoptFlag.isSet(INIT_SYSTEM)) {
Thomas Witkowski's avatar
Thomas Witkowski committed
106
107
108
      solution = adoptProblem->getSolution();
      rhs = adoptProblem->getRHS();
      systemMatrix = adoptProblem->getSystemMatrix();
109
110
111
    }

    // === create solver ===
Thomas Witkowski's avatar
Thomas Witkowski committed
112
    if (solver) {
113
114
115
116
117
118
      WARNING("solver already created\n");
    } else {
      if (initFlag.isSet(INIT_SOLVER)) {
	createSolver();
      } 
      if (adoptProblem && adoptFlag.isSet(INIT_SOLVER)) {
Thomas Witkowski's avatar
Thomas Witkowski committed
119
120
	TEST_EXIT(!solver)("solver already created\n");
	solver = adoptProblem->getSolver();
121
122
123
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
124
    if (!solver) 
125
126
127
128
129
130
131
      WARNING("no solver created\n");

    // === create estimator ===
    if (initFlag.isSet(INIT_ESTIMATOR)) {
      createEstimator();
    } 
    if (adoptProblem && adoptFlag.isSet(INIT_ESTIMATOR)) {
Thomas Witkowski's avatar
Thomas Witkowski committed
132
      estimator = adoptProblem->getEstimator();
133
134
135
136
137
138
139
    } 

    // === create marker ===
    if (initFlag.isSet(INIT_MARKER)) {
      createMarker();
    } 
    if (adoptProblem && adoptFlag.isSet(INIT_MARKER)) {
140
      marker = adoptProblem->getMarker();
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    } 


    // === create file writer ===
    if (initFlag.isSet(INIT_FILEWRITER)) {
      createFileWriter();
    }

    
    // === read serialization and init mesh ===
    
    // There are two possiblities where the user can define a serialization
    // to be read from disk. Either by providing the parameter -rs when executing
    // the program or in the init file. The -rs parameter is always checked first,
    // because it can be added automatically when  rescheduling the program
    // before timeout of the runqueue.

    int readSerialization = 0;
159
    std::string serializationFilename = "";
160
161
162
163
164
165
166
    GET_PARAMETER(0, "argv->rs", &serializationFilename);

    // If the parameter -rs is set, we do nothing here, because the problem will be
    // deserialized in the constructor of a following AdaptInstationary initialization.
    if (!serializationFilename.compare("")) {
      int readSerializationWithAdaptInfo = 0;

Thomas Witkowski's avatar
Thomas Witkowski committed
167
      GET_PARAMETER(0, name + "->input->read serialization", "%d", 
168
		    &readSerialization);
Thomas Witkowski's avatar
Thomas Witkowski committed
169
      GET_PARAMETER(0, name + "->input->serialization with adaptinfo", "%d",
170
171
172
173
174
175
176
		    &readSerializationWithAdaptInfo);

      // The serialization file is only read, if the adaptInfo part should not be used.
      // If the adaptInfo part should be also read, the serialization file will be read
      // in the constructor of the AdaptInstationary problem, because we do not have here
      // the adaptInfo object.
      if (readSerialization && !readSerializationWithAdaptInfo) {
Thomas Witkowski's avatar
Thomas Witkowski committed
177
	GET_PARAMETER(0, name + "->input->serialization filename", 
178
179
180
181
		      &serializationFilename);
	TEST_EXIT(serializationFilename != "")("no serialization file\n");

	MSG("Deserialization from file: %s\n", serializationFilename.c_str());
182
	std::ifstream in(serializationFilename.c_str());
183
184
185
	deserialize(in);
	in.close();
      } else {
186
	int globalRefinements = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
187
	GET_PARAMETER(0, meshes[0]->getName() + "->global refinements", "%d", 
188
189
		      &globalRefinements);

190
	// Initialize the meshes if there is no serialization file.
191
192
	for (int i = 0; i < static_cast<int>(meshes.size()); i++)
	  if (initFlag.isSet(INIT_MESH) && meshes[i] && !(meshes[i]->isInitialized()))
Thomas Witkowski's avatar
Thomas Witkowski committed
193
	    meshes[i]->initialize();	    
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

	// === read value file and use it for the mesh values ===
	std::string valueFilename("");
	GET_PARAMETER(0, meshes[0]->getName() + "->value file name", &valueFilename); 
	if (valueFilename.length()) {     
	  ValueReader::readValue(valueFilename,
				 meshes[0],
				 solution->getDOFVector(0),
				 meshes[0]->getMacroFileInfo());
	  meshes[0]->clearMacroFileInfo();
	}

	// === do global refinements ===
	for (int i = 0; i < static_cast<int>(meshes.size()); i++)
	  if (initFlag.isSet(INIT_MESH) && meshes[i])
Thomas Witkowski's avatar
Thomas Witkowski committed
209
	    refinementManager->globalRefine(meshes[i], globalRefinements);
210
211
212
213
214
215
216
217
218
219
      }
    }

    doOtherStuff();
  }

  void ProblemVec::createMesh() 
  {
    FUNCNAME("ProblemVec::createMesh()");

Thomas Witkowski's avatar
Thomas Witkowski committed
220
    componentMeshes.resize(nComponents);
221
    std::map<int, Mesh*> meshForRefinementSet;
222
223
    char number[3];

224
    std::string meshName("");
Thomas Witkowski's avatar
Thomas Witkowski committed
225
    GET_PARAMETER(0, name + "->mesh", &meshName);
226
    TEST_EXIT(meshName != "")("no mesh name specified\n");
227
    int dim = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
228
    GET_PARAMETER(0, name + "->dim", "%d", &dim);
229
    TEST_EXIT(dim)("no problem dimension specified!\n");
230

231
    for (int i = 0; i < nComponents; i++) {
232
      sprintf(number, "%d", i);
233
      int refSet = -1;
Thomas Witkowski's avatar
Thomas Witkowski committed
234
      GET_PARAMETER(0, name + "->refinement set[" + number + "]", "%d", &refSet);
235
      if (refSet < 0) {
236
237
	refSet = 0;
      }
238
      if (meshForRefinementSet[refSet] == NULL) {
Thomas Witkowski's avatar
Thomas Witkowski committed
239
	Mesh *newMesh = new Mesh(meshName, dim);
240
	meshForRefinementSet[refSet] = newMesh;
Thomas Witkowski's avatar
Thomas Witkowski committed
241
242
	meshes.push_back(newMesh);
	nMeshes++;
243
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
244
      componentMeshes[i] = meshForRefinementSet[refSet];
245
246
247
    }
    switch(dim) {
    case 1:
Thomas Witkowski's avatar
Thomas Witkowski committed
248
249
      coarseningManager = new CoarseningManager1d();
      refinementManager = new RefinementManager1d();
250
251
      break;
    case 2:
Thomas Witkowski's avatar
Thomas Witkowski committed
252
253
      coarseningManager = new CoarseningManager2d();
      refinementManager = new RefinementManager2d();
254
255
      break;
    case 3:
Thomas Witkowski's avatar
Thomas Witkowski committed
256
257
      coarseningManager = new CoarseningManager3d();
      refinementManager = new RefinementManager3d();
258
259
260
261
262
263
264
265
266
267
      break;
    default:
      ERROR_EXIT("invalid dim!\n");
    }
  }

  void ProblemVec::createFESpace()
  {
    FUNCNAME("ProblemVec::createFESpace()");

268
    std::map< std::pair<Mesh*, int>, FiniteElemSpace*> feSpaceMap;
269
    int dim = -1;
Thomas Witkowski's avatar
Thomas Witkowski committed
270
    GET_PARAMETER(0, name + "->dim", "%d", &dim);
271
    TEST_EXIT(dim != -1)("no problem dimension specified!\n");
272

273
    componentSpaces.resize(nComponents, NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
274
    traverseInfo.resize(nComponents);
275

276
    for (int i = 0; i < nComponents; i++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
277
      char number[3];
278
      sprintf(number, "%d", i);
Thomas Witkowski's avatar
Thomas Witkowski committed
279
280
      int degree = 1;
      GET_PARAMETER(0, name + "->polynomial degree[" + number + "]","%d", &degree);
281

282
      TEST_EXIT(componentSpaces[i] == NULL)("feSpace already created\n");
283

Thomas Witkowski's avatar
Thomas Witkowski committed
284
      if (feSpaceMap[std::pair<Mesh*, int>(componentMeshes[i], degree)] == NULL) {
Thomas Witkowski's avatar
Thomas Witkowski committed
285
286
287
	stringstream s;
	s << name << "->feSpace[" << i << "]";

288
	FiniteElemSpace *newFESpace = 
Thomas Witkowski's avatar
Thomas Witkowski committed
289
290
	  FiniteElemSpace::provideFESpace(NULL, Lagrange::getLagrange(dim, degree),
					  componentMeshes[i], s.str());
Thomas Witkowski's avatar
Thomas Witkowski committed
291
	feSpaceMap[std::pair<Mesh*, int>(componentMeshes[i], degree)] = newFESpace;
292
	feSpaces.push_back(newFESpace);
293
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
294
295
296
297
298
299
300
301
      componentSpaces[i] = feSpaceMap[std::pair<Mesh*, int>(componentMeshes[i], degree)];
    }

    for (int i = 0; i < nComponents; i++) {
      for (int j = 0; j < nComponents; j++) {
	traverseInfo.getMatrix(i, j).setFESpace(componentSpaces[i], componentSpaces[j]);
      }
      traverseInfo.getVector(i).setFESpace(componentSpaces[i]);
302
303
304
    }

    // create dof admin for vertex dofs if neccessary
Thomas Witkowski's avatar
Thomas Witkowski committed
305
306
307
    for (int i = 0; i < static_cast<int>(meshes.size()); i++) {
      if (meshes[i]->getNumberOfDOFs(VERTEX) == 0) {
	DimVec<int> ln_dof(meshes[i]->getDim(), DEFAULT_VALUE, 0);
308
	ln_dof[VERTEX]= 1;
Thomas Witkowski's avatar
Thomas Witkowski committed
309
	meshes[i]->createDOFAdmin("vertex dofs", ln_dof);      
310
311
312
313
314
315
316
317
318
319
      }
    }
  }

  void ProblemVec::createMatricesAndVectors()
  {
    FUNCNAME("ProblemVec::createMatricesAndVectors()");

    // === create vectors and system matrix ===

Thomas Witkowski's avatar
Thomas Witkowski committed
320
    systemMatrix = new Matrix<DOFMatrix*>(nComponents, nComponents);
Thomas Witkowski's avatar
Thomas Witkowski committed
321
    systemMatrix->set(NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
322
323
    rhs = new SystemVector("rhs", componentSpaces, nComponents);
    solution = new SystemVector("solution", componentSpaces, nComponents);
324
325

    char number[10];
326
    std::string numberedName;
Thomas Witkowski's avatar
Thomas Witkowski committed
327
    for (int i = 0; i < nComponents; i++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
328
      (*systemMatrix)[i][i] = new DOFMatrix(componentSpaces[i], 
329
					     componentSpaces[i], "A_ii");
Thomas Witkowski's avatar
Thomas Witkowski committed
330
      (*systemMatrix)[i][i]->setCoupleMatrix(false);
331
      sprintf(number, "[%d]", i);
332
      numberedName = "rhs" + std::string(number);
Thomas Witkowski's avatar
Thomas Witkowski committed
333
      rhs->setDOFVector(i, new DOFVector<double>(componentSpaces[i], numberedName));
Thomas Witkowski's avatar
Thomas Witkowski committed
334
      numberedName = name + std::string(number);
Thomas Witkowski's avatar
Thomas Witkowski committed
335
      solution->setDOFVector(i, new DOFVector<double>(componentSpaces[i], 
336
						       numberedName));
Thomas Witkowski's avatar
Thomas Witkowski committed
337
338
      solution->getDOFVector(i)->setCoarsenOperation(COARSE_INTERPOL);
      solution->getDOFVector(i)->set(0.0);
339
340
341
342
343
344
345
346
    }
  }

  void ProblemVec::createSolver()
  {
    FUNCNAME("ProblemVec::createSolver()");

    // === create solver ===
347
    std::string solverType("0");
Thomas Witkowski's avatar
Thomas Witkowski committed
348
    GET_PARAMETER(0, name + "->solver", &solverType);
349
350
    OEMSolverCreator *solverCreator = 
      dynamic_cast<OEMSolverCreator*>(CreatorMap<OEMSolver>::getCreator(solverType));
351
    TEST_EXIT(solverCreator)("no solver type\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
352
353
354
    solverCreator->setName(name + "->solver");
    solver = solverCreator->create();
    solver->initParameters();
355
356
357
358
359
360
361
  }

  void ProblemVec::createEstimator()
  {
    FUNCNAME("ProblemVec::createEstimator()");

    // create and set leaf data prototype
Thomas Witkowski's avatar
Thomas Witkowski committed
362
363
    for (int i = 0; i < static_cast<int>(meshes.size()); i++) {
      meshes[i]->setElementDataPrototype
Thomas Witkowski's avatar
Thomas Witkowski committed
364
	(new LeafDataEstimatableVec(new LeafDataCoarsenableVec));
365
366
367
    }  

    char number[3];
368
    std::string estName;
369

Thomas Witkowski's avatar
Thomas Witkowski committed
370
371
    for (int i = 0; i < nComponents; i++) {
      TEST_EXIT(estimator[i] == NULL)("estimator already created\n");
372
      sprintf(number, "%d", i);
Thomas Witkowski's avatar
Thomas Witkowski committed
373
      estName = name + "->estimator[" + std::string(number) + "]";
374
375

      // === create estimator ===
376
      std::string estimatorType("0");
377
378
379
380
      GET_PARAMETER(0, estName, &estimatorType);
      EstimatorCreator *estimatorCreator = 
	dynamic_cast<EstimatorCreator*>(
					CreatorMap<Estimator>::getCreator(estimatorType));
Thomas Witkowski's avatar
Thomas Witkowski committed
381
      if (estimatorCreator) {
382
383
	estimatorCreator->setName(estName);
	estimatorCreator->setRow(i);
Thomas Witkowski's avatar
Thomas Witkowski committed
384
	if (estimatorType == "recovery") {
385
	  dynamic_cast<RecoveryEstimator::Creator*>(estimatorCreator)->
Thomas Witkowski's avatar
Thomas Witkowski committed
386
	    setSolution(solution->getDOFVector(i));
387
	}
Thomas Witkowski's avatar
Thomas Witkowski committed
388
	estimator[i] = estimatorCreator->create();
389
390
391
      }


Thomas Witkowski's avatar
Thomas Witkowski committed
392
393
394
395
396
      if (estimator[i]) {
	for (int j = 0; j < nComponents; j++) {
	  estimator[i]->addSystem((*systemMatrix)[i][j], 
				   solution->getDOFVector(j), 
				   rhs->getDOFVector(j));
397
398
399
400
401
402
403
404
405
	}
      }
    }
  }

  void ProblemVec::createMarker()
  {
    FUNCNAME("ProblemVec::createMarker()");

406
    std::string numberedName;
407
    char number[10];
Thomas Witkowski's avatar
Thomas Witkowski committed
408
    int nMarkersCreated = 0;
409

410
    for (int i = 0; i < nComponents; i++) {
411
      sprintf(number, "[%d]", i);
Thomas Witkowski's avatar
Thomas Witkowski committed
412
      numberedName = name + "->marker" + std::string(number);
413
414
      marker[i] = Marker::createMarker(numberedName, i);
      if (marker[i]) {
Thomas Witkowski's avatar
Thomas Witkowski committed
415
416
417
418
419
420
	nMarkersCreated++;

	// If there is more than one marker, and all components are defined
	// on the same mesh, the maximum marking has to be enabled.
 	if ((nMarkersCreated > 1) && (nMeshes == 1))
 	  marker[i]->setMaximumMarking(true);
421
422
423
424
425
426
427
428
429
430
      }
    }
  }

  void ProblemVec::createFileWriter()
  {
    FUNCNAME("ProblemVec::createFileWriter()");
  

    // Create one filewriter for all components of the problem
Thomas Witkowski's avatar
Thomas Witkowski committed
431
    std::string numberedName  = name + "->output";
432
    std::string filename = "";
433
434
435
    GET_PARAMETER(0, numberedName + "->filename", &filename);

    if (filename != "") {
436
      std::vector< DOFVector<double>* > solutionList(nComponents);
437

438
      for (int i = 0; i < nComponents; i++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
439
	TEST_EXIT(componentMeshes[0] == componentMeshes[i])
440
441
	  ("All Meshes have to be equal to write a vector file.\n");

Thomas Witkowski's avatar
Thomas Witkowski committed
442
	solutionList[i] = solution->getDOFVector(i);
443
444
      }

Thomas Witkowski's avatar
Thomas Witkowski committed
445
      fileWriters.push_back(new FileWriter(numberedName,
Thomas Witkowski's avatar
Thomas Witkowski committed
446
					    componentMeshes[0],
447
448
449
450
451
452
					    solutionList));
    }


    // Create own filewriters for each components of the problem
    char number[10];
453
    for (int i = 0; i < nComponents; i++) {
454
      sprintf(number, "[%d]", i);
Thomas Witkowski's avatar
Thomas Witkowski committed
455
      numberedName  = name + "->output" + std::string(number);
456
457
458
459
      filename = "";
      GET_PARAMETER(0, numberedName + "->filename", &filename);

      if (filename != "") {
Thomas Witkowski's avatar
Thomas Witkowski committed
460
	fileWriters.push_back(new FileWriter(numberedName, 
Thomas Witkowski's avatar
Thomas Witkowski committed
461
					      componentMeshes[i], 
Thomas Witkowski's avatar
Thomas Witkowski committed
462
					      solution->getDOFVector(i)));
463
464
465
466
467
468
      }
    }


    // Check for serializer
    int writeSerialization = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
469
    GET_PARAMETER(0, name + "->write serialization", "%d", &writeSerialization);
470
    if (writeSerialization) {
Thomas Witkowski's avatar
Thomas Witkowski committed
471
472
      MSG("Use are using the obsolete parameter: %s->write serialization\n", name.c_str());
      MSG("Please use instead the following parameter: %s->output->write serialization\n", name.c_str());
473
474
475
      ERROR_EXIT("Usage of an obsolete parameter (see message above)!\n");
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
476
    GET_PARAMETER(0, name + "->output->write serialization", "%d", &writeSerialization);
477
    if (writeSerialization) {
Thomas Witkowski's avatar
Thomas Witkowski committed
478
      fileWriters.push_back(new Serializer<ProblemVec>(this));
479
480
481
482
483
484
485
    }
  }

  void ProblemVec::doOtherStuff()
  {
  }

486
  void ProblemVec::solve(AdaptInfo *adaptInfo, bool fixedMatrix)
487
488
489
  {
    FUNCNAME("Problem::solve()");

Thomas Witkowski's avatar
Thomas Witkowski committed
490
    if (!solver) {
491
492
493
494
495
496
497
498
499
      WARNING("no solver\n");
      return;
    }

#ifdef _OPENMP
    double wtime = omp_get_wtime();
#endif

    clock_t first = clock();
500
501
    int iter = solver->solveSystem(solverMatrix, *solution, *rhs);

502
#ifdef _OPENMP
Thomas Witkowski's avatar
Thomas Witkowski committed
503
504
    INFO(info, 8)("solution of discrete system needed %.5f seconds system time / %.5f seconds wallclock time\n",
		  TIME_USED(first, clock()), omp_get_wtime() - wtime);
505
#else
Thomas Witkowski's avatar
Thomas Witkowski committed
506
507
    INFO(info, 8)("solution of discrete system needed %.5f seconds\n", 
		  TIME_USED(first, clock()));
508
509
510
#endif

    adaptInfo->setSolverIterations(iter);
Thomas Witkowski's avatar
Thomas Witkowski committed
511
512
513
    adaptInfo->setMaxSolverIterations(solver->getMaxIterations());
    adaptInfo->setSolverTolerance(solver->getTolerance());
    adaptInfo->setSolverResidual(solver->getResidual());
514
515
516
517
518
519
  }

  void ProblemVec::estimate(AdaptInfo *adaptInfo) 
  {
    FUNCNAME("ProblemVec::estimate()");

Thomas Witkowski's avatar
Thomas Witkowski committed
520
521
    VtkWriter::writeFile(solution->getDOFVector(0), "test.vtu");

522
523
    clock_t first = clock();

524
525
526
527
#ifdef _OPENMP
    double wtime = omp_get_wtime();
#endif

528
    if (computeExactError) {
Thomas Witkowski's avatar
Thomas Witkowski committed
529
      computeError(adaptInfo);
530
531
    } else {
      for (int i = 0; i < nComponents; i++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
532
	Estimator *scalEstimator = estimator[i];
533
534
535
536
537
538
539
540
541
542
	
	if (scalEstimator) {
	  scalEstimator->estimate(adaptInfo->getTimestep());
	  adaptInfo->setEstSum(scalEstimator->getErrorSum(), i);
	  adaptInfo->setEstMax(scalEstimator->getErrorMax(), i);
	  adaptInfo->setTimeEstSum(scalEstimator->getTimeEst(), i);
	  adaptInfo->setTimeEstMax(scalEstimator->getTimeEstMax(), i);
	} else {
	  WARNING("no estimator for component %d\n" , i);
	}
543
544
545
      }
    }

546
#ifdef _OPENMP
Thomas Witkowski's avatar
Thomas Witkowski committed
547
548
    INFO(info, 8)("estimation of the error needed %.5f seconds system time / %.5f seconds wallclock time\n",
		  TIME_USED(first, clock()), omp_get_wtime() - wtime);
549
#else
Thomas Witkowski's avatar
Thomas Witkowski committed
550
551
    INFO(info, 8)("estimation of the error needed %.5f seconds\n",
		  TIME_USED(first, clock()));
552
553
554

#endif

555
556
557
558
559
560
561
562
563
564
565
  }

  Flag ProblemVec::markElements(AdaptInfo *adaptInfo) 
  {
    FUNCNAME("ProblemVec::markElements()");

    // to enforce albert-like behavior: refinement even if space tolerance
    // here is reached already because of time adaption
    allowFirstRefinement();

    Flag markFlag = 0;
566
    for (int i = 0; i < nComponents; i++) {
567
      if (marker[i]) {
Thomas Witkowski's avatar
Thomas Witkowski committed
568
	markFlag |= marker[i]->markMesh(adaptInfo, componentMeshes[i]);
569
570
571
572
      } else {
	WARNING("no marker for component %d\n", i);
      }
    }
573
    
574
575
576
577
578
579
580
    return markFlag;
  }

  Flag ProblemVec::refineMesh(AdaptInfo *adaptInfo) 
  {
    FUNCNAME("ProblemVec::refineMesh()");

581
582
    //    if (adaptInfo->getTimestepNumber() == 9) return 0;

Thomas Witkowski's avatar
Thomas Witkowski committed
583
    int nMeshes = static_cast<int>(meshes.size());
584
    Flag refineFlag = 0;
585
586
587
588
    for (int i = 0; i < nMeshes; i++)
      if (adaptInfo->isRefinementAllowed(i))
	refineFlag |= refinementManager->refineMesh(meshes[i]);

589
590
591
592
593
594
595
    return refineFlag;
  }

  Flag ProblemVec::coarsenMesh(AdaptInfo *adaptInfo) 
  {
    FUNCNAME("ProblemVec::coarsenMesh()");

Thomas Witkowski's avatar
Thomas Witkowski committed
596
    int nMeshes = static_cast<int>(meshes.size());
597
    Flag coarsenFlag = 0;
598
599
    for (int i = 0; i < nMeshes; i++)
      if (adaptInfo->isCoarseningAllowed(i))
Thomas Witkowski's avatar
Thomas Witkowski committed
600
	coarsenFlag |= coarseningManager->coarsenMesh(meshes[i]);
601
602
603
604
605
606
607
608

    return coarsenFlag;
  }

  Flag ProblemVec::oneIteration(AdaptInfo *adaptInfo, Flag toDo)
  {
    FUNCNAME("ProblemVec::oneIteration()");

Thomas Witkowski's avatar
Thomas Witkowski committed
609
    if (allowFirstRef) {
610
      for (int i = 0; i < nComponents; i++) {
611
612
	adaptInfo->allowRefinement(true, i);
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
613
      allowFirstRef = false;
614
    } else {
615
      for (int i = 0; i < nComponents; i++) {
616
617
618
619
620
621
622
623
624
625
626
	if (adaptInfo->spaceToleranceReached(i)) {
	  adaptInfo->allowRefinement(false, i);
	} else {
	  adaptInfo->allowRefinement(true, i);	
	}
      }
    }

    return StandardProblemIteration::oneIteration(adaptInfo, toDo);
  }

627
628
  void ProblemVec::buildAfterCoarsen(AdaptInfo *adaptInfo, Flag flag,
				     bool asmMatrix, bool asmVector)
629
630
631
632
633
  {
    FUNCNAME("ProblemVec::buildAfterCoarsen()");

    clock_t first = clock();

634
635
636
637
#ifdef _OPENMP
    double wtime = omp_get_wtime();
#endif

638
    for (int i = 0; i < static_cast<int>(meshes.size()); i++)
Thomas Witkowski's avatar
Thomas Witkowski committed
639
      meshes[i]->dofCompress();
640
641
642

    Flag assembleFlag = 
      flag | 
Thomas Witkowski's avatar
Thomas Witkowski committed
643
644
      (*systemMatrix)[0][0]->getAssembleFlag() | 
      rhs->getDOFVector(0)->getAssembleFlag()  |
645
646
647
648
649
650
      Mesh::CALL_LEAF_EL                        | 
      Mesh::FILL_COORDS                         |
      Mesh::FILL_DET                            |
      Mesh::FILL_GRD_LAMBDA |
      Mesh::FILL_NEIGH;

Thomas Witkowski's avatar
Thomas Witkowski committed
651
    if (useGetBound)
652
      assembleFlag |= Mesh::FILL_BOUND;
Thomas Witkowski's avatar
Thomas Witkowski committed
653

654
    for (int i = 0; i < nComponents; i++) {
655
      MSG("%d DOFs for %s\n", 
656
657
	  componentSpaces[i]->getAdmin()->getUsedSize(), 
	  componentSpaces[i]->getName().c_str());
658

Thomas Witkowski's avatar
Thomas Witkowski committed
659
      rhs->getDOFVector(i)->set(0.0);
660
      for (int j = 0; j < nComponents; j++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
661
	if ((*systemMatrix)[i][j]) {
662
663
664
665
666
	  DOFMatrix*                   dof_matrix= (*systemMatrix)[i][j];
	  DOFMatrix::base_matrix_type& base_matrix= dof_matrix->getBaseMatrix();

	  int nnz_per_row= 0;
	  if (num_rows(base_matrix) != 0)
Thomas Witkowski's avatar
Thomas Witkowski committed
667
	    nnz_per_row= int(double(base_matrix.nnz()) / num_rows(base_matrix) * 1.2); 
668
	  if (nnz_per_row < 5) 
Thomas Witkowski's avatar
Thomas Witkowski committed
669
	    nnz_per_row= 5;
670
671
672
673

	  // Correct dimensionality of matrix
	  base_matrix.change_dim(componentSpaces[i]->getAdmin()->getUsedSize(), 
				 componentSpaces[j]->getAdmin()->getUsedSize());
Thomas Witkowski's avatar
Thomas Witkowski committed
674
675

	  set_to_zero(base_matrix);
676
677
	  
	  // Reuse old sparsity information (if available) or default
678
	  //	  dof_matrix->startInsertion(nnz_per_row);
679
	}
680
681
682
      }
    }

Thomas Witkowski's avatar
Thomas Witkowski committed
683
684
    traverseInfo.updateStatus();

Thomas Witkowski's avatar
Thomas Witkowski committed
685
    for (int i = 0; i < nComponents; i++) {
686
      for (int j = 0; j < nComponents; j++) {
687

688
689
690
691
	// Only if this variable is true, the current matrix will be assembled.	
	bool assembleMatrix = true;
	// The DOFMatrix which should be assembled (or not, if assembleMatrix
	// will be set to false).
Thomas Witkowski's avatar
Thomas Witkowski committed
692
	DOFMatrix *matrix = (*systemMatrix)[i][j];
693

694
695
	// If the matrix was assembled before and it is marked to be assembled
	// only once, it will not be assembled.
696
	if (assembleMatrixOnlyOnce[i][j] && assembledMatrix[i][j])
697
	  assembleMatrix = false;
Thomas Witkowski's avatar
Thomas Witkowski committed
698
699

	// If there is no DOFMatrix, e.g., if it is completly 0, do not assemble.
700
	if (!matrix || !assembleMatrix)
701
702
	  assembleMatrix = false;

703
704
705
706
707
708
709
	// If the matrix should not be assembled, the rhs vector has to be considered.
	// This will be only done, if i == j. So, if both is not true, we can jump
	// to the next matrix.
	if (!assembleMatrix && i != j) {
	  continue;
	}

710
711
712
	if (assembleMatrix && matrix->getBoundaryManager())
	  matrix->getBoundaryManager()->initMatrix(matrix);

Thomas Witkowski's avatar
Thomas Witkowski committed
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
	if (traverseInfo.getStatus(i, j) == SingleComponentInfo::EQ_SPACES_NO_AUX ||
	    traverseInfo.getStatus(i, j) == SingleComponentInfo::EQ_SPACES_WITH_AUX) {

	  // Row fe space and col fe space are both equal

	  if (traverseInfo.getStatus(i) == SingleComponentInfo::EQ_SPACES_NO_AUX ||
	      traverseInfo.getStatus(i) == SingleComponentInfo::EQ_SPACES_WITH_AUX) {

	    // The simplest case: either the right hand side has no operaters, no aux
	    // fe spaces, or all aux fe spaces are equal to the row and col fe space.

	    assembleOnOneMesh(componentSpaces[i],
			      assembleFlag,
			      assembleMatrix ? matrix : NULL,
			      ((i == j) && asmVector) ? rhs->getDOFVector(i) : NULL);

	  } else if (traverseInfo.getStatus(i) == SingleComponentInfo::EQ_SPACES_WITH_DIF_AUX) {

	    // Row fe space and col fe space are both equal, but right hand side has at
732
	    // least one another aux fe space. 
Thomas Witkowski's avatar
Thomas Witkowski committed
733
734
735
736
737
738

	    assembleOnOneMesh(componentSpaces[i],
			      assembleFlag,
			      assembleMatrix ? matrix : NULL,
			      ((i == j) && asmVector) ? rhs->getDOFVector(i) : NULL);

739
740
	    assembleOnDifMeshes2(componentSpaces[i], 
				 traverseInfo.getAuxFESpace(i, j),
Thomas Witkowski's avatar
Thomas Witkowski committed
741
742
				 assembleFlag,
				 NULL,
743
				 ((i == j) && asmVector) ? rhs->getDOFVector(i) : NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
744
745
746
747
748
749
750

	  } else {
	    ERROR_EXIT("Possible? If yes, not yet implemented!\n");
	  }

	} else if (traverseInfo.getStatus(i, j) == SingleComponentInfo::EQ_SPACES_WITH_DIF_AUX) {
	  
Thomas Witkowski's avatar
Thomas Witkowski committed
751
752
753
	  assembleOnOneMesh(componentSpaces[i],
			    assembleFlag,
			    assembleMatrix ? matrix : NULL,
Thomas Witkowski's avatar
Thomas Witkowski committed
754
			    ((i == j) && asmVector) ? rhs->getDOFVector(i) : NULL);
755
	  
Thomas Witkowski's avatar
Thomas Witkowski committed
756
757
758
759
	  assembleOnDifMeshes2(componentSpaces[i],
			       traverseInfo.getAuxFESpace(i, j),
			       assembleFlag,
			       assembleMatrix ? matrix : NULL,
760
			       ((i == j) && asmVector) ? rhs->getDOFVector(i) : NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
761
762
763
764

	} else if (traverseInfo.getStatus(i, j) ==  SingleComponentInfo::DIF_SPACES_NO_AUX ||
		   traverseInfo.getStatus(i, j) ==  SingleComponentInfo::DIF_SPACES_WITH_AUX) {

Thomas Witkowski's avatar
Thomas Witkowski committed
765
766
767
	  assembleOnDifMeshes(componentSpaces[i], componentSpaces[j],
			      assembleFlag,
			      assembleMatrix ? matrix : NULL,
Thomas Witkowski's avatar
Thomas Witkowski committed
768
769
770
			      ((i == j) && asmVector) ? rhs->getDOFVector(i) : NULL);	  
	} else {
	  ERROR_EXIT("Not yet implemented!\n");
771
	}
Thomas Witkowski's avatar
Thomas Witkowski committed
772

773
774
775
	// TODO: ExitMatrix should be called after finishInsertion!
 	if (assembleMatrix && matrix->getBoundaryManager())
 	  matrix->getBoundaryManager()->exitMatrix(matrix);	  
776
	
Thomas Witkowski's avatar
Thomas Witkowski committed
777
	assembledMatrix[i][j] = true;
778
779
      }

780
      // And now assemble boundary conditions on the vectors
Thomas Witkowski's avatar
Thomas Witkowski committed
781
782
      assembleBoundaryConditions(rhs->getDOFVector(i),
				 solution->getDOFVector(i),
783
				 componentMeshes[i],
784
				 assembleFlag);      
785
    }
786

787
788
    int nnz = 0;

789
790
791
    // Finish insertion
    for (int i = 0; i < nComponents; i++) 
      for (int j = 0; j < nComponents; j++) 
792
 	if ((*systemMatrix)[i][j]) {
793
 	  (*systemMatrix)[i][j]->finishInsertion(); 
794
	  nnz += (*systemMatrix)[i][j]->getBaseMatrix().nnz();
795
	}    
796

797
    solverMatrix.setMatrix(*systemMatrix);
798

Thomas Witkowski's avatar
Thomas Witkowski committed
799
    createPrecon();
800

801
    INFO(info, 8)("fillin of assembled matrix: %d\n", nnz);
802

803
#ifdef _OPENMP
Thomas Witkowski's avatar
Thomas Witkowski committed
804
805
    INFO(info, 8)("buildAfterCoarsen needed %.5f seconds system time / %.5f seconds wallclock time\n",
		  TIME_USED(first, clock()), omp_get_wtime() - wtime);
806
#else
Thomas Witkowski's avatar
Thomas Witkowski committed
807
808
    INFO(info, 8)("buildAfterCoarsen needed %.5f seconds\n", 
		  TIME_USED(first, clock()));
Thomas Witkowski's avatar
Thomas Witkowski committed
809
#endif     
810
811
  }

812
813
  void ProblemVec::createPrecon()
  {
814
    std::string preconType("no");
815
816
817
818
819
    GET_PARAMETER(0, name + "->solver->left precon", &preconType);

    CreatorInterface<ITL_BasePreconditioner> *preconCreator = 
      CreatorMap<ITL_BasePreconditioner>::getCreator(preconType);

Thomas Witkowski's avatar
Thomas Witkowski committed
820
    solver->setLeftPrecon(preconCreator->create(solverMatrix.getMatrix()));
821
822
823
824
825

    preconType= "no";
    GET_PARAMETER(0, name + "->solver->right precon", &preconType);

    preconCreator = CreatorMap<ITL_BasePreconditioner>::getCreator(preconType);
Thomas Witkowski's avatar
Thomas Witkowski committed
826
    solver->setRightPrecon(preconCreator->create(solverMatrix.getMatrix()));
827
828
829
  }


830
831
832
833
  void ProblemVec::writeFiles(AdaptInfo *adaptInfo, bool force) 
  {
    FUNCNAME("ProblemVec::writeFiles()");

834
835
836
837
838
839
840
    clock_t first = clock();

#ifdef _OPENMP
    double wtime = omp_get_wtime();
#endif

    int i;
Thomas Witkowski's avatar
Thomas Witkowski committed
841
    int size = static_cast<int>(fileWriters.size());
842
843
844
845
#ifdef _OPENMP
#pragma omp parallel for schedule(static, 1)
#endif
    for (i = 0; i < size; i++) {
Thomas Witkowski's avatar
Thomas Witkowski committed
846
      fileWriters[i]->writeFiles(adaptInfo, force);
847
    }
848
849
    
#ifdef _OPENMP
Thomas Witkowski's avatar
Thomas Witkowski committed
850
851
852
    INFO(info, 8)("writeFiles needed %.5f seconds system time / %.5f seconds wallclock time\n",
		  TIME_USED(first, clock()),
		  omp_get_wtime() - wtime);
853
#else
Thomas Witkowski's avatar
Thomas Witkowski committed
854
855
    INFO(info, 8)("writeFiles needed %.5f seconds\n",
		  TIME_USED(first, clock()));
856
#endif
857
858
  }

859
  void ProblemVec::interpolInitialSolution(std::vector<AbstractFunction<double, WorldVector<double> >*> *fct) 
860
861
862
  {
    FUNCNAME("ProblemVec::interpolInitialSolution()");

Thomas Witkowski's avatar
Thomas Witkowski committed
863
    solution->interpol(fct);
864
865
866
867
868
  }

  void ProblemVec::addMatrixOperator(Operator *op, 
				     int i, int j,
				     double *factor,
869
870
				     double *estFactor,
				     bool fake)
871
872
  {
    FUNCNAME("ProblemVec::addMatrixOperator()");
Thomas Witkowski's avatar
Thomas Witkowski committed
873
   
Thomas Witkowski's avatar
Thomas Witkowski committed
874
    if (!(*systemMatrix)[i][j]) {
875
      TEST_EXIT(i != j)("should have been created already\n");
Thomas Witkowski's avatar
Thomas Witkowski committed
876
      (*systemMatrix)[i][j] = new DOFMatrix(componentSpaces[i], componentSpaces[j], "");
Thomas Witkowski's avatar
Thomas Witkowski committed
877
878
879
      (*systemMatrix)[i][j]->setCoupleMatrix(true);
      (*systemMatrix)[i][j]->getBoundaryManager()->
	setBoundaryConditionMap((*systemMatrix)[i][i]->getBoundaryManager()->
880
				getBoundaryConditionMap());
Thomas Witkowski's avatar
Thomas Witkowski committed
881
882
883

      if (estimator[i])
	estimator[i]->setNewMatrix(j, (*systemMatrix)[i][j]);
884
    }    
Thomas Witkowski's avatar
Thomas Witkowski committed
885

886
    (*systemMatrix)[i][j]->addOperator(op, factor, estFactor);
Thomas Witkowski's avatar
Thomas Witkowski committed
887

888
889
890
891
892
893
894
895
896
897
898
    if (!fake) {    
      traverseInfo.getMatrix(i, j).setAuxFESpaces(op->getAuxFESpaces()); 
      
      for (int k = 0; k < static_cast<int>(op->getAuxFESpaces().size()); k++) {
	if ((op->getAuxFESpaces())[k]->getMesh() != componentSpaces[i]->getMesh() ||
	    (op->getAuxFESpaces())[k]->getMesh() != componentSpaces[j]->getMesh()) {
	  op->setNeedDualTraverse(true);
	  break;
	}
      }    
    } 
899
900
901
902
  }

  void ProblemVec::addVectorOperator(Operator *op, int i,
				     double *factor,
903
904
				     double *estFactor,
				     bool fake)
905
906
907
  {
    FUNCNAME("ProblemVec::addVectorOperator()");

Thomas Witkowski's avatar
Thomas Witkowski committed
908
909
    rhs->getDOFVector(i)->addOperator(op, factor, estFactor);

910
911
912
913
914
915
916
917
918
919
    if (!fake) {
      traverseInfo.getVector(i).setAuxFESpaces(op->getAuxFESpaces()); 
      
      for (int j = 0; j < static_cast<int>(op->getAuxFESpaces().size()); j++) {
	if ((op->getAuxFESpaces())[j]->getMesh() != componentSpaces[i]->getMesh()) {
	  op->setNeedDualTraverse(true);
	  break;
	}
      }    
    }
920
921
  }

922
  void ProblemVec::addDirichletBC(BoundaryType type, int row, int col,
923
924
925
926
				  AbstractFunction<double, WorldVector<double> >* b)
  {
    FUNCNAME("ProblemVec::addDirichletBC()");

927
928
929
930
931
932
933
934
935
936
937
938
    DirichletBC *dirichletApply = 
      new DirichletBC(type, b, componentSpaces[row], componentSpaces[col], true);
    DirichletBC *dirichletNotApply = 
      new DirichletBC(type, b, componentSpaces[row], componentSpaces[col], false);

    for (int i = 0; i < nComponents; i++) 
      if (systemMatrix && (*systemMatrix)[row][i])
	if (i == col)
	  (*systemMatrix)[row][i]->getBoundaryManager()->addBoundaryCondition(dirichletApply);
	else
	  (*systemMatrix)[row][i]->getBoundaryManager()->addBoundaryCondition(dirichletNotApply);

Thomas Witkowski's avatar
Thomas Witkowski committed
939
    if (rhs)
940
      rhs->getDOFVector(row)->getBoundaryManager()->addBoundaryCondition(dirichletApply);
Thomas Witkowski's avatar
Thomas Witkowski committed
941
    if (solution)
942
      solution->getDOFVector(row)->getBoundaryManager()->addBoundaryCondition(dirichletApply);
943
944
945
946
947
948
949
950
  }

  void ProblemVec::addNeumannBC(BoundaryType type, int row, int col, 
				AbstractFunction<double, WorldVector<double> > *n)
  {
    FUNCNAME("ProblemVec::addNeumannBC()");

    NeumannBC *neumann = 
951
952
      new NeumannBC(type, n, componentSpaces[row],