DOFMatrix.h 16.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// ============================================================================
// ==                                                                        ==
// == AMDiS - Adaptive multidimensional simulations                          ==
// ==                                                                        ==
// ============================================================================
// ==                                                                        ==
// ==  crystal growth group                                                  ==
// ==                                                                        ==
// ==  Stiftung caesar                                                       ==
// ==  Ludwig-Erhard-Allee 2                                                 ==
// ==  53175 Bonn                                                            ==
// ==  germany                                                               ==
// ==                                                                        ==
// ============================================================================
// ==                                                                        ==
// ==  http://www.caesar.de/cg/AMDiS                                         ==
// ==                                                                        ==
// ============================================================================

/** \file DOFMatrix.h */

#ifndef AMDIS_DOFMATRIX_H
#define AMDIS_DOFMATRIX_H

#include <vector>
Thomas Witkowski's avatar
Thomas Witkowski committed
26
#include <set>
27
28
#include <memory>
#include <list>
29
#include <boost/numeric/mtl/mtl.hpp>
30

31
#include "AMDiS_fwd.h"
32
33
34
35
36
37
38
39
40
#include "Global.h"
#include "Flag.h"
#include "RCNeighbourList.h"
#include "DOFAdmin.h"
#include "DOFIterator.h"
#include "DOFIndexed.h"
#include "Boundary.h"
#include "Serializable.h"

41
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
42
43
44
#include "petscao.h"
#endif

45
46
47
48
49
namespace AMDiS {

  /** \ingroup DOFAdministration
   * \brief
   * A DOFMatrix is a sparse matrix representation for matrices that work
50
51
   * on DOFVectors. The underlying matrix type 
   * is a CRS matrix of double.
52
   */
53
  class DOFMatrix : public DOFIndexed<bool>,
54
55
56
                    public Serializable
  {
  public:
57
58
59
60
61
62
63
64
65
66
    /// Type of scalars in the underlying matrix
    typedef double                          value_type;

    /// Type of underlying matrix
    typedef mtl::compressed2D<value_type>       base_matrix_type;

    /// Type of inserter for the base matrix;
    typedef mtl::matrix::inserter<base_matrix_type>  inserter_type;

  private:
Thomas Witkowski's avatar
Thomas Witkowski committed
67
    /// Symbolic constant for an unused matrix entry
68
69
70
71
72
73
74
75
76
77
78
    static const int UNUSED_ENTRY = -1;
    
    /** \brief
     * Symbolic constant for an unused entry which is not followed by any
     * used entry in this row
     */
    static const int NO_MORE_ENTRIES = -2;

  public:    
    DOFMatrix();

Thomas Witkowski's avatar
Thomas Witkowski committed
79
80
    /// Constructs a DOFMatrix with name n and the given row and olumn FESpaces.
    DOFMatrix(const FiniteElemSpace* rowFESpace, const FiniteElemSpace* colFESpace,
Thomas Witkowski's avatar
Thomas Witkowski committed
81
	      std::string n = "");
82

Thomas Witkowski's avatar
Thomas Witkowski committed
83
    /// Copy-Constructor
84
85
    DOFMatrix(const DOFMatrix& rhs);

Thomas Witkowski's avatar
Thomas Witkowski committed
86
    /// Destructor
87
88
    virtual ~DOFMatrix();
  
Thomas Witkowski's avatar
Thomas Witkowski committed
89
    /// Assignment operator.
90
91
92
93
    DOFMatrix& operator=(const DOFMatrix& rhs);

    void copy(const DOFMatrix& rhs);

94
95
96
97
    /// Access underlying matrix directly
    base_matrix_type& getBaseMatrix()
    {
	return matrix;
98
    }
99

100
101
102
103
    /// Access underlying matrix directly (const)
    const base_matrix_type& getBaseMatrix() const
    {
	return matrix;
104
    }
105
106
107
108
109
110
111
112

    // Only to get rid of the abstract functions, I hope they are not used
    std::vector<bool>::iterator begin() {ERROR_EXIT("Shouldn't be used, only fake."); std::vector<bool> v; return v.begin();}
    std::vector<bool>::iterator end() {ERROR_EXIT("Shouldn't be used, only fake."); std::vector<bool> v; return v.end();}
    
    bool dummy; // Must be deleted later
    bool& operator[](int i) {ERROR_EXIT("Shouldn't be used, only fake."); return dummy;}
    const bool& operator[](int i) const {ERROR_EXIT("Shouldn't be used, only fake."); return dummy;}
113
 
114
    /// DOFMatrix does not need to be compressed before assembling, when using MTL4.
115
    void compressDOFIndexed(int first, int last, std::vector<DegreeOfFreedom> &newDOF) {}
116

117
    /// Implements DOFIndexedBase::freeDOFContent()
118
119
    virtual void freeDOFContent(int index);

120
    /// Returns \ref coupleMatrix.
Thomas Witkowski's avatar
Thomas Witkowski committed
121
122
    inline bool isCoupleMatrix() { 
      return coupleMatrix; 
123
    }
124

125
    /// Returns \ref coupleMatrix.
Thomas Witkowski's avatar
Thomas Witkowski committed
126
127
    inline void setCoupleMatrix(bool c) { 
      coupleMatrix = c; 
128
    }
129

130
    /// a * x + y
Thomas Witkowski's avatar
Thomas Witkowski committed
131
    void axpy(double a, const DOFMatrix& x, const DOFMatrix& y);
132

133
    /// Multiplication with a scalar.
134
135
    void scal(double s);

Thomas Witkowski's avatar
Thomas Witkowski committed
136
137
138
139
140
141
    /** \brief
     * Adds an operator to the DOFMatrix. A factor, that is multipled
     * to the operator, and a multilier factor for the estimator may be
     * also given.
     */
    void addOperator(Operator *op, double* factor = NULL, double* estFactor = NULL);
142

143
    inline std::vector<double*>::iterator getOperatorFactorBegin() {
144
      return operatorFactor.begin();
145
    }
146

147
    inline std::vector<double*>::iterator getOperatorFactorEnd() {
148
      return operatorFactor.end();
149
    }
150

151
    inline std::vector<double*>::iterator getOperatorEstFactorBegin() {
152
      return operatorEstFactor.begin();
153
    }
154

155
    inline std::vector<double*>::iterator getOperatorEstFactorEnd() {
156
      return operatorEstFactor.end();
157
    }
158

159
    inline std::vector<Operator*>::iterator getOperatorsBegin() {
160
      return operators.begin();
161
    }
162

163
    inline std::vector<Operator*>::iterator getOperatorsEnd() {
164
      return operators.end();
165
    }
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

    Flag getAssembleFlag();

    /** \brief
     * Updates the matrix matrix by traversing the underlying mesh and assembling
     * the element contributions into the matrix. Information about the 
     * computation of element matrices and connection of local and global DOFs is
     * stored in minfo; the flags for the mesh traversal are stored at 
     * minfo->fill_flags which specifies the elements to be visited and 
     * information that should be present on the elements for the calculation of 
     * the element matrices and boundary information (if minfo->boundBas is not
     * NULL). On the elements, information about the row DOFs is accessed by 
     * minfo->rowBas using info->row_admin; this vector is also used for the 
     * column DOFs if minfo->nCol is less or equal zero, or minfo->col_admin or 
     * minfo->colBas is a NULL pointer; if row and column DOFs are the same, the 
     * boundary type of the DOFs is accessed by minfo->boundBas if 
     * minfo->boundBas is not a NULL pointer; then the element matrix is 
     * computed by minfo->fillElementMatrix(el info, minfo->myFill); these 
     * contributions, multiplied by minfo->factor, are eventually added to matrix
     * by a call of addElementMatrix() with all information about row and column 
     * DOFs, the element matrix, and boundary types, if available;
     * updateMatrix() only adds element contributions; this makes several calls 
     * for the assemblage of one matrix possible; before the first call, the 
     * matrix should be cleared by calling clear dof matrix().
     */
  
192
    void assemble(double factor, ElInfo *elInfo, const BoundaryType *bound);
193

194
195
    void assemble(double factor, ElInfo *elInfo, const BoundaryType *bound,
		  Operator *op);
196

197
198
199
    void assemble(double factor, 
		  ElInfo *rowElInfo, ElInfo *colElInfo,
		  ElInfo *smallElInfo, ElInfo *largeElInfo,
Thomas Witkowski's avatar
Thomas Witkowski committed
200
201
		  const BoundaryType *bound,
		  Operator *op = NULL);
202

Thomas Witkowski's avatar
Thomas Witkowski committed
203
204
205
206
207
208
209
    void assemble2(double factor, 
		   ElInfo *mainElInfo, ElInfo *auxElInfo,
		   ElInfo *smallElInfo, ElInfo *largeElInfo,
		   const BoundaryType *bound, 
		   Operator *op = NULL);

    /// Adds an element matrix to \ref matrix
210
211
212
213
214
    void addElementMatrix(double sign, 
			  const ElementMatrix& elMat, 
			  const BoundaryType *bound,
			  bool add = true);

Thomas Witkowski's avatar
Thomas Witkowski committed
215
216
217
218
219
220
221
    /* \brief
     * That function must be called after the matrix assembling has been finished. 
     * This makes it possible to start some cleanup or matrix data compressing 
     * procedures.
     */
    void finishAssembling();

222
223
224
225
226
227
228
229
230
231
    /** \brief
     * Enable insertion for assembly. You can optionally give an upper limit for
     * entries per row (per column for CCS matrices).  Choosing this parameter
     * too small can induce perceivable overhead for compressed matrices.  Thus,
     * it's better to choose a bit too large than too small.
     */
    void startInsertion(int nnz_per_row= 10)
    {
      if (inserter) 
	delete inserter, inserter= 0; 
232

233
      inserter= new inserter_type(matrix, nnz_per_row);
234
    }
235

236
237
238
239
240
241
242
243
244
245
    /** \brief
     *  Finishes insertion. For compressed matrix types, this is where the 
     *  compression happens.
     */
    void finishInsertion()
    {
      TEST_EXIT(inserter)("Inserter wasn't used or is already finished.");
      
      delete inserter;
      inserter= 0;
246
    }
247
248
249
250
251
252
253

    /** \brief
     * Returns whether restriction should be performed after coarsening
     * (false by default)
     */
    virtual bool coarseRestrict() {
      return false;
254
    }
255

Thomas Witkowski's avatar
Thomas Witkowski committed
256
    /// Returns const \ref rowFESpace
257
258
    const FiniteElemSpace* getRowFESpace() const { 
      return rowFESpace; 
259
    }
260

261
    /// Returns const \ref colFESpace
262
263
    const FiniteElemSpace* getColFESpace() const { 
      return colFESpace; 
264
    }
265

266
    /// Returns const \ref rowFESpace
267
268
    const FiniteElemSpace* getFESpace() const { 
      return rowFESpace; 
269
    }
270

271
    /// Returns number of rows (\ref matrix.size())
272
    inline int getSize() const { 
273
      return num_rows(matrix);
274
    }
275

Thomas Witkowski's avatar
Thomas Witkowski committed
276
277
278
279
280
281
    /** \brief
     * Returns the number of used rows (equal to number of used DOFs in
     * the row FE space).
     */
    inline int getUsedSize() const {
      return rowFESpace->getAdmin()->getUsedSize();
282
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
283

284
    /// Returns \ref name
285
    inline const std::string& getName() const { 
286
      return name; 
287
    }
288

289
    /// Resizes \ref matrix to n rows
290
    inline void resize(int n) { 
291
292
293
      TEST_EXIT_DBG(n >= 0)("Can't resize DOFMatrix to negative size\n");
      //      matrix.change_dim(n, n);
      //WARNING("Obsolete function without effect -- Peter\n");
294
    }
295

296
    /// Returns value at logical indices a,b
297
    double logAcc(DegreeOfFreedom a, DegreeOfFreedom b) const;
298

299
    /// Changes col at logical indices a,b to c 
300
    void changeColOfEntry(DegreeOfFreedom a, DegreeOfFreedom b, DegreeOfFreedom c);
301
302
303
304
305

    /** \brief
     * Creates an entry with logical indices irow, icol if there is no entry
     * yet. Than sign * entry is added to the value at this logical indices
     */
306
307
308
    void addSparseDOFEntry(double sign,
			   int irow, int jcol, double entry,
			   bool add = true);
309

Thomas Witkowski's avatar
Thomas Witkowski committed
310
311
    void removeRowsWithDBC(std::set<int> *rows);

312
    /// Prints \ref matrix to stdout
313
314
    void print() const;

315
    /// Removes all matrix entries
316
317
318
319
    void clear()
    {
	set_to_zero(matrix);
    }
320

321
    /// Test whether \ref matrix is symmetric. Exits if not.
322
323
324
325
    void test();

    bool symmetric();

326
    inline std::vector<Operator*> getOperators() { 
327
      return operators; 
328
    }
329
    
330
    inline std::vector<double*> getOperatorFactor() { 
331
      return operatorFactor; 
332
    }
333

334
    inline std::vector<double*> getOperatorEstFactor() { 
335
      return operatorEstFactor; 
336
    }
337
338
339

    inline BoundaryManager* getBoundaryManager() const { 
      return boundaryManager; 
340
    }
341

342
    /// Returns a pointer to \ref applyDBCs.
Thomas Witkowski's avatar
Thomas Witkowski committed
343
344
345
346
    std::set<int>* getApplyDBCs() {
      return &applyDBCs;
    }

347
348
    inline void setBoundaryManager(BoundaryManager *bm) {
      boundaryManager = bm;
349
    }
350
351

    void createPictureFile(const char* filename, int dim);
352
   
353
354
355
  private:
    template <typename T>
    void s_write(::std::ostream &out, const T& value)
356
    {
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
      out.write(reinterpret_cast<const char*>(&value), sizeof value);
    }

  public:    
    void serialize(::std::ostream &out) 
    {
      using namespace mtl; 

      typedef traits::range_generator<tag::major, base_matrix_type>::type c_type;
      typedef traits::range_generator<tag::nz, c_type>::type              ic_type;

      typedef Collection<base_matrix_type>::size_type                     size_type;
      typedef Collection<base_matrix_type>::value_type                    value_type;
      
      traits::row<base_matrix_type>::type                                 row(matrix); 
      traits::col<base_matrix_type>::type                                 col(matrix);
      traits::const_value<base_matrix_type>::type                         value(matrix); 

      size_type rows= num_rows(matrix), cols= num_cols(matrix), total= matrix.nnz();
      s_write(out, rows);
      s_write(out, cols);
      s_write(out, total);

      for (c_type cursor(mtl::begin<tag::major>(matrix)), cend(mtl::end<tag::major>(matrix)); 
	   cursor != cend; ++cursor)
	for (ic_type icursor(mtl::begin<tag::nz>(cursor)), icend(mtl::end<tag::nz>(cursor)); 
	     icursor != icend; ++icursor) {
	  size_type   my_row= row(*icursor), my_col= col(*icursor);
	  value_type  my_value= value(*icursor);
	  s_write(out, my_row);
	  s_write(out, my_col);
	  s_write(out, my_value);
	}
390
    }
391

392
393
394
395
396
397
  private:
    template <typename T>
    void s_read(::std::istream &in, T& value)
    {
      in.read(reinterpret_cast<char*>(&value), sizeof value);
    }
398

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  public:    
    void deserialize(::std::istream &in) 
    {
      using namespace mtl;

      typedef Collection<base_matrix_type>::size_type                     size_type;
      typedef Collection<base_matrix_type>::value_type                    value_type;
      
      size_type rows, cols, total;
      s_read(in, rows);
      s_read(in, cols);
      s_read(in, total);

      // Prepare matrix insertion
      clear();
      // matrix.change_dim(rows, cols) // do we want this?
      inserter_type ins(matrix);

      for (size_type i= 0; i < total; ++i) {
	size_type   my_row, my_col;
	value_type  my_value;
	s_read(in, my_row);
	s_read(in, my_col);
	s_read(in, my_value);
	ins(my_row, my_col) << my_value;
424
      }
425
    }
426

427
    ///
428
429
    int memsize();

430
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
431
432
433
434
435
    /// Sets the petsc application ordering object to map dof indices.
    void useApplicationOrdering(AO *ao) {
      applicationOrdering = ao;
    }
#endif
436
437
438
439
440
441
442
443
444
445
446
447
448
449

  protected:
    /** \brief
     * Pointer to a FiniteElemSpace with information about corresponding row DOFs
     * and basis functions
     */
    const FiniteElemSpace *rowFESpace;

    /** \brief
     * Pointer to a FiniteElemSpace with information about corresponding 
     * column DOFs and basis functions
     */
    const FiniteElemSpace *colFESpace;

450
    /// Name of the DOFMatrix
451
    std::string name;
452

453
    /// Sparse matrix, type is a template parameter by default compressed2D<double>
454
    base_matrix_type matrix;
455

456
    /// Used while mesh traversal
457
458
459
460
461
462
    static DOFMatrix *traversePtr;
  
    /** \brief
     * Pointers to all operators of the equation systems. Are used in the
     * assembling process.
     */
463
    std::vector<Operator*> operators;
464
465
466
467
468
    
    /** \brief
     * Defines for each operator a factor which is used to scal the element
     * matrix after the assembling process of the operator.
     */
469
    std::vector<double*> operatorFactor;
470

471
    ///
472
    std::vector<double*> operatorEstFactor;
473

474
    ///
475
476
    BoundaryManager *boundaryManager;

477
478
479
480
    /** \brief
     * If false, the matrix is a diagonal matrix within a matrix of DOF matrices.
     * Otherwise the value is true, and the matrix is an off-diagonal matrix.
     */
481
482
    bool coupleMatrix;

483
    /// Temporary variable used in assemble()
Thomas Witkowski's avatar
Thomas Witkowski committed
484
485
    ElementMatrix *elementMatrix;

486
487
488
489
490
491
492
    /* \brief
     * A set of row indices. When assembling the DOF matrix, all rows, that
     * correspond to a dof at a dirichlet boundary, are ignored and the row is
     * left blank. After assembling, the diagonal element of the matrix must be
     * set to 1. The indices of all rows, where this should be done, are stored
     * in this set.
     */    
Thomas Witkowski's avatar
Thomas Witkowski committed
493
494
    std::set<int> applyDBCs;

495
#ifdef HAVE_PARALLEL_DOMAIN_AMDIS
496
497
498
499
    /// Petsc application ordering to map dof indices.
    AO *applicationOrdering;
#endif

500
    /// Inserter object: implemented as pointer, allocated and deallocated as needed
501
    inserter_type *inserter;
502
      
503
504
505
506
507
508
509
510
511
512
    friend class DOFAdmin;
    friend class DOFVector<double>;
    friend class DOFVector<unsigned char>;
    friend class DOFVector<int>;
    friend class DOFVector<WorldVector<double> >;
  };

}

#endif  // AMDIS_DOFMATRIX_H