MeshDistributor.h 19.1 KB
Newer Older
1
2
3
4
5
6
// ============================================================================
// ==                                                                        ==
// == AMDiS - Adaptive multidimensional simulations                          ==
// ==                                                                        ==
// ============================================================================
// ==                                                                        ==
7
// ==  TU Dresden                                                            ==
8
// ==                                                                        ==
9
10
11
// ==  Institut für Wissenschaftliches Rechnen                               ==
// ==  Zellescher Weg 12-14                                                  ==
// ==  01069 Dresden                                                         ==
12
13
14
15
// ==  germany                                                               ==
// ==                                                                        ==
// ============================================================================
// ==                                                                        ==
16
// ==  https://gforge.zih.tu-dresden.de/projects/amdis/                      ==
17
18
19
// ==                                                                        ==
// ============================================================================

20
/** \file MeshDistributor.h */
21

22
23
#ifndef AMDIS_MESHDISTRIBUTOR_H
#define AMDIS_MESHDISTRIBUTOR_H
24
25
26


#include <map>
27
#include <set>
28
#include <vector>
Thomas Witkowski's avatar
Thomas Witkowski committed
29
#include <mpi.h>
30

Thomas Witkowski's avatar
Thomas Witkowski committed
31
#include "Global.h"
32
33
#include "ProblemTimeInterface.h"
#include "ProblemIterationInterface.h"
34
#include "FiniteElemSpace.h"
35
#include "AdaptInfo.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
36
#include "parallel/InteriorBoundary.h"
37
#include "Serializer.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
38
#include "BoundaryManager.h"
39
40
#include "AMDiS_fwd.h"

41
namespace AMDiS {
42
  
43
44
  class ParMetisPartitioner;

45
  class MeshDistributor
46
  {
47
  protected:
Thomas Witkowski's avatar
Thomas Witkowski committed
48
49
50
51
52
53
54
55
56
57
58
59
    /// Defines a mapping type from DOFs to rank numbers.
    typedef std::map<const DegreeOfFreedom*, int> DofToRank;

    /// Defines a mapping type from DOFs to a set of rank numbers.
    typedef std::map<const DegreeOfFreedom*, std::set<int> > DofToPartitions;

    /// Defines a mapping type from rank numbers to sets of DOFs.
    typedef std::map<int, DofContainer> RankToDofContainer;

    /// Defines a mapping type from DOF indices to DOF indices.
    typedef std::map<DegreeOfFreedom, DegreeOfFreedom> DofMapping;

60
61
62
    /// Defines a mapping type from DOFs to boolean values.
    typedef std::map<const DegreeOfFreedom*, bool> DofToBool;

Thomas Witkowski's avatar
Thomas Witkowski committed
63
    /// Defines a mapping type from DOF indices to boolean values.
64
    typedef std::map<DegreeOfFreedom, bool> DofIndexToBool;
Thomas Witkowski's avatar
Thomas Witkowski committed
65

Thomas Witkowski's avatar
Thomas Witkowski committed
66
67
68
    /// Forward type (it maps rank numbers to the interior boundary objects).
    typedef InteriorBoundary::RankToBoundMap RankToBoundMap;

Thomas Witkowski's avatar
Thomas Witkowski committed
69
70
    typedef std::map<const DegreeOfFreedom*, DegreeOfFreedom> DofIndexMap;

71
    typedef std::map<int, DofMapping> PeriodicDofMap;
72
73
    
    typedef std::vector<MeshStructure> MeshCodeVec;
74

75
  public:
76
77
78
    MeshDistributor(std::string str);
		          
    virtual ~MeshDistributor() {}
79

80
    void initParallelization(AdaptInfo *adaptInfo);
81

82
83
84
    void exitParallelization(AdaptInfo *adaptInfo);

    void addProblemStat(ProblemVec *probVec);
85

86
87
88
89
90
91
92
93
94
    /** \brief
     * This function checks if the mesh has changed on at least on rank. In this case,
     * the interior boundaries are adapted on all ranks such that they fit together on
     * all ranks. Furthermore the function \ref updateLocalGlobalNumbering() is called
     * to update the dof numberings and mappings on all rank due to the new mesh
     * structure.
     */
    void checkMeshChange();

95
    void updateDofAdmins();    
96

97
98
99
100
101
102
103
    /** \brief
     * Test, if the mesh consists of macro elements only. The mesh partitioning of
     * the parallelization works for macro meshes only and would fail, if the mesh
     * is already refined in some way. Therefore, this function will exit the program
     * if it finds a non macro element in the mesh.
     */
    void testForMacroMesh();
104
105
106
107
108
109

    /// Set for each element on the partitioning level the number of leaf elements.
    double setElemWeights(AdaptInfo *adaptInfo);

    void partitionMesh(AdaptInfo *adaptInfo);

110
111
112
113
114
115
116
    inline virtual std::string getName() 
    { 
      return name; 
    }
    
    /// Returns \ref nRankDOFs, the number of DOFs in the rank mesh.
    inline int getNumberRankDofs() 
117
    {
118
      return nRankDofs;
119
    }
120

121
    inline int getNumberOverallDofs()
122
    {
123
      return nOverallDofs;
124
    }
125

126
    inline DegreeOfFreedom mapLocalToGlobal(DegreeOfFreedom dof)
127
    {
128
      return mapLocalGlobalDofs[dof];
129
    }
130

131
132
133
134
135
    inline DegreeOfFreedom mapLocalToDofIndex(DegreeOfFreedom dof)
    {
      return mapLocalDofIndex[dof];
    }

136
    inline int getPeriodicMapping(int type, int globalDofIndex)
137
    {
138
139
140
141
142
143
144
145
146
      TEST_EXIT_DBG(periodicDof[type].count(globalDofIndex) == 1)
	("Should not happen!\n");

      return periodicDof[type][globalDofIndex];
    }

    inline std::set<int>& getPerDofAssociations(int globalDofIndex)
    {      
      return perDofAssociations[globalDofIndex];
147
    }
148

149
    inline bool isPeriodicDof(int globalDofIndex)
150
    {
151
152
153
154
155
156
      return (perDofAssociations.count(globalDofIndex) > 0);
    }

    inline bool isPeriodicDof(int globalDofIndex, int type)
    {
      return (periodicDof[type].count(globalDofIndex) > 0);
157
158
    }

159
160
161
162
    inline bool getIsRankDof(DegreeOfFreedom dof)
    {
      return isRankDof[dof];
    }
163

164
    inline long getLastMeshChangeIndex()
165
    {
166
      return lastMeshChangeIndex;
167
    }
168

169
170
171
172
    inline int getRstart()
    {
      return rstart;
    }
173

174
    inline int getMpiRank()
175
    {
176
      return mpiRank;
177
    }
178

179
180
181
    inline MPI::Intracomm& getMpiComm()
    {
      return mpiComm;
182
183
    }

184
    inline RankToDofContainer& getSendDofs()
185
    {
186
      return sendDofs;
187
188
    }

189
    inline RankToDofContainer& getRecvDofs()
190
    {
191
      return recvDofs;
192
    }
193

194
    // Writes all data of this object to an output stream.
195
    void serialize(std::ostream &out);
196

197
    // Reads the object data from an input stream.
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    void deserialize(std::istream &in);

    /** \brief
     * This function must be used if the values of a DOFVector must be synchronised
     * over all ranks. That means, that each rank sends the values of the DOFs, which
     * are owned by the rank and lie on an interior bounday, to all other ranks also
     * having these DOFs.
     *
     * This function must be used, for example, after the lineary system is solved, or
     * after the DOFVector is set by some user defined functions, e.g., initial
     * solution functions.
     */    
    void synchVector(DOFVector<double> &vec);

    /** \brief
     * Works in the same way as the function above defined for DOFVectors. Due to
     * performance, this function does not call \ref synchVector for each DOFVector,
     * but instead sends all values of all DOFVectors all at once.
     */
    void synchVector(SystemVector &vec);

219
  protected:
220
    /** \brief
Thomas Witkowski's avatar
Thomas Witkowski committed
221
     * Determines the interior boundaries, i.e. boundaries between ranks, and stores
222
223
     * all information about them in \ref interiorBoundary.
     */
224
    void createInteriorBoundaryInfo();
225

Thomas Witkowski's avatar
Thomas Witkowski committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    /** \brief
     * Deterimes the interior boundaries between ranks, that are based on the 
     * neighbourhood information of the macro elements. That means that in 2d the
     * function search for all edge based interior boundaries and in 3d for all face
     * based interior boundaries. This function cannot find boundaries of substructure
     * elements, i.e. vertex boundaries in 2d and vertex and edge boundaries in 3d.
     */
    void createMacroElementInteriorBoundaryInfo();

    /** \brief
     * Determines all interior boundaries between rank that consist of element's
     * substructures. In 2d these may be only vertices. In 3d there may be also
     * interior boundaries consisting of either a whole edge or of a single vertex.
     */
    void createSubstructureInteriorBoundaryInfo();

242
243
244
    /// Removes all macro elements from the mesh that are not part of ranks partition.
    void removeMacroElements();

245
246
    /// Creates from a macro mesh a correct local and global DOF index numbering.
    void createLocalGlobalNumbering();
247

248
249
    /// Updates the local and global DOF numbering after the mesh has been changed.
    void updateLocalGlobalNumbering();
250

251
252
253
254
255
    /** \brief
     * Creates to all dofs in rank's partition that are on a periodic boundary the
     * mapping from dof index to the other periodic dof indices. This information
     * is stored in \ref periodicDof.
     */
256
257
    void createPeriodicMap();

258
259
    /** \brief
     * This function create new mappings from local to global indices, 
260
     * \ref mapLocalGlobalDofs, and from local to dof indices, \ref mapLocalDofIndex.
261
262
263
264
265
266
267
268
269
270
271
272
273
274
     * Furthermore, using the first argument the dof indices in ranks partition are
     * changed.
     * 
     * \param[in] rankDofsNewLocalIndex       Map from dof pointers of all dofs in rank
     *                                        to new dof indices.
     * \param[in] rankOwnedDofsNewLocalIndex  Map from dof pointers of dofs owned by
     *                                        the rank to the new local index.
     * \param[in] rankDofsNewGlobalIndex      Map from dof pointers of all dofs in rank
     *                                        to the new global index.
     */
    void createLocalMappings(DofIndexMap &rankDofsNewLocalIndex,
			     DofIndexMap &rankOwnedDofsNewLocalIndex,
			     DofIndexMap &rankDofsNewGlobalIndex);

275
276
    /** \brief
     * This function traverses the whole mesh, i.e. before it is really partitioned,
Thomas Witkowski's avatar
Thomas Witkowski committed
277
278
279
     * and collects information about which DOF corresponds to which rank. Can only
     * be used, if \ref partitionVec is set correctly. This is only the case, when
     * the macro mesh is partitioned.
280
     *
281
282
283
284
285
     * \param[out] partitionDOFs   Stores to each DOF pointer the set of ranks the DOF
     *                             is part of.
     * \param[out] rankDOFs        Stores all rank DOFs.
     * \param[out] boundaryDOFs    Stores all DOFs in ranks partition that are on an 
     *                             interior boundary but correspond to another rank.
286
     */
287
    void createDofMemberInfo(DofToPartitions& partitionDofs,
Thomas Witkowski's avatar
n  
Thomas Witkowski committed
288
289
			     DofContainer& rankOwnedDofs,
			     DofContainer& rankAllDofs,
290
			     DofToRank& boundaryDofs,
291
			     DofToBool& isVertexDof);
Thomas Witkowski's avatar
Thomas Witkowski committed
292

293
294
295
296
297
298
299
300
301
302
303
304
305
    /** \brief
     * Checks for all given interior boundaries if the elements fit together on both
     * sides of the boundaries. If this is not the case, the mesh is adapted. Because
     * refinement of a certain element may forces the refinement of other elements,
     * it is not guaranteed that all rank's meshes fit together after this function
     * terminates. Hence, it must be called until a stable mesh refinement is reached.
     * If the mesh has  been changed by this function, it returns true. Otherwise, it
     * returns false, i.e., the given interior boundaries fit together on both sides.
     *
     * \param[in] allBound   Defines a map from rank to interior boundaries which 
     *                       should be checked.
     */
    bool checkAndAdaptBoundary(RankToBoundMap &allBound);
Thomas Witkowski's avatar
Thomas Witkowski committed
306
    
307
308
309
310
311
312
313
    /** \brief
     * This functions create a Paraview file with the macro mesh where the elements
     * are colored by the partition they are part of. This function can be used for
     * debugging.
     */
    void writePartitioningMesh(std::string filename);

314
315
316
317
    /// Removes all periodic boundary condition information from all matrices and
    /// vectors of all stationary problems and from the mesh itself.
    void removePeriodicBoundaryConditions();

Thomas Witkowski's avatar
Thomas Witkowski committed
318
    // Removes all periodic boundaries from a given boundary map.
319
    void removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap);
Thomas Witkowski's avatar
Thomas Witkowski committed
320

321
322
    bool fitElementToMeshCode(MeshStructure &code, 
			      Element *el, 
323
324
			      GeoIndex subObj,
			      int ithObj, 
325
326
			      int elType,
			      bool reverseMode);
327
328
    
    bool fitElementToMeshCode2(MeshStructure &code, 
329
			       TraverseStack &stack,
330
331
			       GeoIndex subObj,
			       int ithObj, 
332
333
			       int elType,
			       bool reverseMode);
334

335
336
337
338
339
340
341
342
343
344
345
346
347
    /// Writes a vector of dof pointers to an output stream.
    void serialize(std::ostream &out, DofContainer &data);

    /// Reads a vector of dof pointers from an input stream.
    void deserialize(std::istream &in, DofContainer &data,
		     std::map<int, const DegreeOfFreedom*> &dofMap);

    /// Writes a \ref RankToDofContainer to an output stream.
    void serialize(std::ostream &out, RankToDofContainer &data);

    /// Reads a \ref RankToDofContainer from an input stream.
    void deserialize(std::istream &in, RankToDofContainer &data,
		     std::map<int, const DegreeOfFreedom*> &dofMap);
348

349
350
351
    /// Writes a periodic dof mapping to an output stream.
    void serialize(std::ostream &out, PeriodicDofMap &data);

352
353
    void serialize(std::ostream &out, std::map<int, std::set<int> >& data);

354
355
356
    /// Reads a periodic dof mapping from an input stream.
    void deserialize(std::istream &in, PeriodicDofMap &data);

357
358
    void deserialize(std::istream &in, std::map<int, std::set<int> >& data);

359
360
361
362
    /// Writes a mapping from dof pointers to some values to an output stream.
    template<typename T>
    void serialize(std::ostream &out, std::map<const DegreeOfFreedom*, T> &data)
    {
363
364
      FUNCNAME("ParallelDomainBase::serialize()");

365
      int mapSize = data.size();
366
      SerUtil::serialize(out, mapSize);
367
368
369
370
      for (typename std::map<const DegreeOfFreedom*, T>::iterator it = data.begin();
	   it != data.end(); ++it) {
	int v1 = (*(it->first));
	T v2 = it->second;
371
372
	SerUtil::serialize(out, v1);
	SerUtil::serialize(out, v2);
373
374
375
376
377
378
379
380
      }
    }

    /// Reads a mapping from dof pointer to some values from an input stream.
    template<typename T>
    void deserialize(std::istream &in, std::map<const DegreeOfFreedom*, T> &data,
		     std::map<int, const DegreeOfFreedom*> &dofMap)
    {
381
382
      FUNCNAME("ParallelDomainBase::deserialize()");

383
      int mapSize = 0;
384
      SerUtil::deserialize(in, mapSize);
385
386
387
      for (int i = 0; i < mapSize; i++) {
	int v1 = 0;
	T v2;
388
389
	SerUtil::deserialize(in, v1);
	SerUtil::deserialize(in, v2);
390
391
392

	TEST_EXIT_DBG(dofMap.count(v1) != 0)("Cannot find DOF %d in map!\n", v1);

393
394
395
396
	data[dofMap[v1]] = v2;
      }
    }
		        
397
  protected:
Thomas Witkowski's avatar
Thomas Witkowski committed
398
    ///
399
    std::vector<ProblemVec*> probStat;
Thomas Witkowski's avatar
Thomas Witkowski committed
400

401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
    /// The rank of the current process.
    int mpiRank;

    /// Overall number of processes.
    int mpiSize;

    /** \brief
     * MPI communicator collected all processes, which should
     * be used for calculation. The Debug procces is not included
     * in this communicator.
     */
    MPI::Intracomm mpiComm;

    /// Name of the problem (as used in the init files)
    std::string name;

417
418
419
    /// Finite element space of the problem.
    FiniteElemSpace *feSpace;

420
421
422
    /// Mesh of the problem.
    Mesh *mesh;

423
424
425
426
427
428
429
    /** \brief
     * A refinement manager that should be used on the mesh. It is used to refine
     * elements at interior boundaries in order to fit together with elements on the
     * other side of the interior boundary.
     */    
    RefinementManager *refineManager;

430
431
432
    /// Info level.
    int info;

433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
    /// Pointer to the paritioner which is used to devide a mesh into partitions.
    ParMetisPartitioner *partitioner;

    /// Weights for the elements, i.e., the number of leaf elements within this element.
    std::map<int, double> elemWeights;

    /// Is true, if the mesh was not partitioned before, otherwise it's false.
    bool initialPartitionMesh;

    /** \brief
     * Stores to every coarse element index the number of the partition it 
     * corresponds to.
     */
    std::map<int, int> partitionVec;

    /** \brief
     * Stores an old partitioning of elements. To every element index the number
     * of the parition it corresponds to is stored.
     */
    std::map<int, int> oldPartitionVec;    
453
   
454
    /// Number of DOFs in the rank mesh.
455
    int nRankDofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
456

457
    /// Number of DOFs in the whole domain.
458
459
    int nOverallDofs;

Thomas Witkowski's avatar
Thomas Witkowski committed
460
    /** \brief 
Thomas Witkowski's avatar
Thomas Witkowski committed
461
462
463
464
465
466
467
468
469
470
471
472
     * Defines the interior boundaries of the domain that result from partitioning
     * the whole mesh. Contains only the boundaries, which are owned by the rank, i.e.,
     * the object gives for every neighbour rank i the boundaries this rank owns and 
     * shares with rank i.
     */
    InteriorBoundary myIntBoundary;
    
    /** \brief
     * Defines the interior boundaries of the domain that result from partitioning
     * the whole mesh. Contains only the boundaries, which are not owned by the rank,
     * i.e., the object gives for every neighbour rank i the boundaries that are
     * owned by rank i and are shared with this rank.
Thomas Witkowski's avatar
Thomas Witkowski committed
473
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
474
    InteriorBoundary otherIntBoundary;
Thomas Witkowski's avatar
Thomas Witkowski committed
475

476
    /** \brief
477
478
     * Defines the periodic boundaries with other ranks. Periodic boundaries have
     * no owner, as it is the case of interior boundaries.
479
480
481
     */
    InteriorBoundary periodicBoundary;

482
483
484
485
    /** \brief
     * This map contains for each rank the list of dofs the current rank must send
     * to exchange solution dofs at the interior boundaries.
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
486
    RankToDofContainer sendDofs;
487
488

    /** \brief
489
490
491
     * This map contains for each rank the list of DOFs from which the current rank 
     * will receive DOF values (i.e., this are all DOFs at an interior boundary). The
     * DOF indices are given in rank's local numbering.
492
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
493
    RankToDofContainer recvDofs;
494
495

    /// Maps local to global dof indices.
496
    DofMapping mapLocalGlobalDofs;
497

Thomas Witkowski's avatar
Thomas Witkowski committed
498
    /// Maps local dof indices to real dof indices.
499
    DofMapping mapLocalDofIndex;  
500
501
502
503
504
505

    /** \brief
     * Maps all DOFs in ranks partition to a bool value. If it is true, the DOF is
     * owned by the rank. Otherwise, its an interior boundary DOF that is owned by
     * another rank.
     */
506
507
    DofIndexToBool isRankDof;

508
509
    /** \brief
     * Maps every dof pointer in ranks macro mesh to a boolean variable indicating 
510
     * whether this dof is a vertex dof (true) or not (false).
511
     */
512
    DofToBool vertexDof;
Thomas Witkowski's avatar
n  
Thomas Witkowski committed
513

514
515
516
517
518
    /** \brief
     * If periodic boundaries are used, this map stores to each dof in rank's 
     * partition, that is on periodic boundaries, the corresponding periodic dofs.
     * The mapping is defined by using global dof indices.
     */
519
520
    PeriodicDofMap periodicDof;

521
522
    std::map<int, std::set<int> > perDofAssociations;

523
    /// Is the index of the first row of the linear system, which is owned by the rank.
Thomas Witkowski's avatar
n  
Thomas Witkowski committed
524
    int rstart;
525

526
527
528
529
530
531
532
    /** \brief
     * If the problem definition has been read from a serialization file, this 
     * variable is true, otherwise it is false. This variable is used to stop the
     * initialization function, if the problem definition has already been read from
     * a serialization file.
     */
    bool deserialized;
533

534
535
536
    /// Denotes whether there exists a filewriter for this object.
    bool writeSerializationFile;

537
538
539
540
541
    /** \brief
     * Stores the mesh change index. This is used to recognize changes in the mesh 
     * structure (e.g. through refinement or coarsening managers).
     */
    long lastMeshChangeIndex;
542

543
544
545
546
547
    /// This variable is true, if the macro elements are consistent with all other
    /// data structures. Within the initialization and during mesh redistribution this
    /// may not be the case.
    bool macroElementStructureConsisten;

548
    friend class ParallelDebug;
549
550
551
  };
}

552
#endif // AMDIS_MESHDISTRIBUTOR_H