MeshDistributor.h 21.7 KB
Newer Older
1
2
3
4
5
6
// ============================================================================
// ==                                                                        ==
// == AMDiS - Adaptive multidimensional simulations                          ==
// ==                                                                        ==
// ============================================================================
// ==                                                                        ==
7
// ==  TU Dresden                                                            ==
8
// ==                                                                        ==
9
10
11
// ==  Institut fr 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"
Thomas Witkowski's avatar
Thomas Witkowski committed
35
#include "parallel/InteriorBoundary.h"
36
#include "Serializer.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
37
#include "BoundaryManager.h"
38
#include "ElementObjectData.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
72
73
    /// Mapps a boundar type, i.e., a boundary identifier index, to a periodic 
    /// dof mapping.
    typedef std::map<BoundaryType, DofMapping> PeriodicDofMap;
74
75
    
    typedef std::vector<MeshStructure> MeshCodeVec;
76

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

82
    void initParallelization();
83

84
    void exitParallelization();
85
86

    void addProblemStat(ProblemVec *probVec);
87

88
89
90
91
92
93
94
95
96
    /** \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();

97
    void updateDofAdmins();    
98

99
100
101
102
103
104
105
    /** \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();
106
107

    /// Set for each element on the partitioning level the number of leaf elements.
108
    void setInitialElementWeights();
109

110
111
112
113
    inline virtual std::string getName() 
    { 
      return name; 
    }
114
115
116
117
118
119

    /// Returns \ref feSpace.
    inline const FiniteElemSpace* getFeSpace()
    {
      return feSpace;
    }
120
121
122
    
    /// Returns \ref nRankDOFs, the number of DOFs in the rank mesh.
    inline int getNumberRankDofs() 
123
    {
124
      return nRankDofs;
125
    }
126

127
    /// Returns \ref nOverallDofs, the global number of DOFs.
128
    inline int getNumberOverallDofs()
129
    {
130
      return nOverallDofs;
131
    }
132

133
    /// Maps a local dof to its global index.
134
    inline DegreeOfFreedom mapLocalToGlobal(DegreeOfFreedom dof)
135
    {
136
      return mapLocalGlobalDofs[dof];
137
    }
138

139
    /// Maps a local dof to its local index.
140
141
142
143
144
    inline DegreeOfFreedom mapLocalToDofIndex(DegreeOfFreedom dof)
    {
      return mapLocalDofIndex[dof];
    }

145
146
    /// Returns for a global dof index its periodic mapping for a given boundary type.
    inline int getPeriodicMapping(BoundaryType type, int globalDofIndex)
147
    {
148
149
150
151
152
153
      TEST_EXIT_DBG(periodicDof[type].count(globalDofIndex) == 1)
	("Should not happen!\n");

      return periodicDof[type][globalDofIndex];
    }

154
155
156
    /// For a given global DOF index, this function returns the set of periodic
    /// associations, i.e., the boundary types the DOF is associated to, for this DOF.
    inline std::set<BoundaryType>& getPerDofAssociations(int globalDofIndex)
157
    {      
158
      return periodicDofAssociations[globalDofIndex];
159
    }
160

161
    /// Returns true, if the DOF (global index) is a periodic DOF.
162
    inline bool isPeriodicDof(int globalDofIndex)
163
    {
164
      return (periodicDofAssociations.count(globalDofIndex) > 0);
165
166
    }

167
168
169
    /// Returns true, if the DOF (global index) is a periodic DOF for the given
    /// boundary type.
    inline bool isPeriodicDof(int globalDofIndex, BoundaryType type)
170
171
    {
      return (periodicDof[type].count(globalDofIndex) > 0);
172
173
    }

174
175
    /// Return true, if the given DOF is owned by the rank. If false, the DOF is in
    /// rank's partition, but is owned by some other rank.
176
177
178
179
    inline bool getIsRankDof(DegreeOfFreedom dof)
    {
      return isRankDof[dof];
    }
180

181
    inline long getLastMeshChangeIndex()
182
    {
183
      return lastMeshChangeIndex;
184
    }
185

186
187
188
189
    inline int getRstart()
    {
      return rstart;
    }
190

191
    inline int getMpiRank()
192
    {
193
      return mpiRank;
194
    }
195

196
197
198
    inline MPI::Intracomm& getMpiComm()
    {
      return mpiComm;
199
200
    }

201
    inline RankToDofContainer& getSendDofs()
202
    {
203
      return sendDofs;
204
205
    }

206
    inline RankToDofContainer& getRecvDofs()
207
    {
208
      return recvDofs;
209
    }
210

211
    // Writes all data of this object to an output stream.
212
    void serialize(std::ostream &out);
213

214
    // Reads the object data from an input stream.
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
    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);

236
  protected:
237
    /** \brief
Thomas Witkowski's avatar
Thomas Witkowski committed
238
     * Determines the interior boundaries, i.e. boundaries between ranks, and stores
239
240
     * all information about them in \ref interiorBoundary.
     */
241
    void createInteriorBoundaryInfo();
242

243
    void createBoundaryDataStructure();
Thomas Witkowski's avatar
Thomas Witkowski committed
244

245
246
247
    /// Removes all macro elements from the mesh that are not part of ranks partition.
    void removeMacroElements();

248
249
    /// Creates from a macro mesh a correct local and global DOF index numbering.
    void createLocalGlobalNumbering();
250

251
252
    /// Updates the local and global DOF numbering after the mesh has been changed.
    void updateLocalGlobalNumbering();
253

254
255
256
257
258
    /** \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.
     */
259
260
    void createPeriodicMap();

261
262
    void createMacroElementInfo();

263
264
    /** \brief
     * This function create new mappings from local to global indices, 
265
     * \ref mapLocalGlobalDofs, and from local to dof indices, \ref mapLocalDofIndex.
266
267
268
269
270
271
272
273
274
275
276
277
278
279
     * 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);

280
281
    /** \brief
     * This function traverses the whole mesh, i.e. before it is really partitioned,
Thomas Witkowski's avatar
Thomas Witkowski committed
282
283
284
     * 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.
285
     *
286
287
288
289
290
     * \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.
291
     */
292
    void createDofMemberInfo(DofToPartitions& partitionDofs,
Thomas Witkowski's avatar
n  
Thomas Witkowski committed
293
294
			     DofContainer& rankOwnedDofs,
			     DofContainer& rankAllDofs,
295
			     DofToRank& boundaryDofs);
Thomas Witkowski's avatar
Thomas Witkowski committed
296

297
298
299
300
301
302
303
304
305
306
307
308
309
    /** \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);
310
311
312
313
314
315
316
317
  
    /** \brief
     * Checks if is required to repartition the mesh. If this is the case, a new
     * partition will be created and the mesh will be redistributed between the
     * ranks.
     */
    void repartitionMesh();

318
319
320
321
322
323
324
    /** \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);

325
326
327
    /// Sets \ref isRankDof to all matrices and rhs vectors in all stationary problems.
    void setRankDofs();

328
329
330
331
    /// 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
332
    // Removes all periodic boundaries from a given boundary map.
333
    void removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap);
Thomas Witkowski's avatar
Thomas Witkowski committed
334

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    /** \brief
     * Starts the procedure to fit a given edge/face of an element with a mesh
     * structure code. This functions prepares some data structures and call
     * then \ref fitElementToMeshCode, that mainly refines the element such that
     * it fits to the mesh structure code.
     *
     * \param[in] code         The mesh structure code to which the edge/face of
     *                         an element must be fitted.
     * \param[in] el           Pointer to the element.
     * \param[in] subObj       Defines whether an edge or a face must be fitted.
     * \param[in] ithObj       Defines which edge/face must be fitted.
     * \param[in] elType       Element type of the element (only important in 3D).
     * \param[in] reverseMode  Defines, whether the mesh structure code is given
     *                         in reverse mode, i.e., left and right children where
     *                         changed when the code was created.
     */
    bool startFitElementToMeshCode(MeshStructure &code, 
				   Element *el, 
				   GeoIndex subObj,
				   int ithObj, 
				   int elType,
				   bool reverseMode);
    
    /** \brief
     * Recursively fits a given mesh structure code to an edge/face of an element.
     * This function is always initialy called from \ref startFitElementToMeshCode.
     *
     * \param[in] code         The mesh structure code which is used to fit an
     *                         edge/face of an element.
     * \param[in] stack        A traverse stack object. The upper most element in this
     *                         stack must be used for fitting the mesh structure code
     *                         at the current position.
     * \param[in] subObj       Defines whether an edge or a face must be fitted.
     * \param[in] ithObj       Defines which edge/face must be fitted.
     * \param[in] reverseMode  Defines, whether the mesh structure code is given
     *                         in reverse mode, i.e., left and right children where
     *                         changed when the code was created.
     */
373
    bool fitElementToMeshCode(MeshStructure &code, 
374
			      TraverseStack &stack,
375
			      GeoIndex subObj,
376
			      int ithObj,
377
			      bool reverseMode);
378

379
380
381
382
383
384
385
386
387
388
389
390
391
    /// 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);
392

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

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

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

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

403
404
405
406
    /// 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)
    {
407
408
      FUNCNAME("ParallelDomainBase::serialize()");

409
      int mapSize = data.size();
410
      SerUtil::serialize(out, mapSize);
411
412
413
414
      for (typename std::map<const DegreeOfFreedom*, T>::iterator it = data.begin();
	   it != data.end(); ++it) {
	int v1 = (*(it->first));
	T v2 = it->second;
415
416
	SerUtil::serialize(out, v1);
	SerUtil::serialize(out, v2);
417
418
419
420
421
422
423
424
      }
    }

    /// 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)
    {
425
426
      FUNCNAME("ParallelDomainBase::deserialize()");

427
      int mapSize = 0;
428
      SerUtil::deserialize(in, mapSize);
429
430
431
      for (int i = 0; i < mapSize; i++) {
	int v1 = 0;
	T v2;
432
433
	SerUtil::deserialize(in, v1);
	SerUtil::deserialize(in, v2);
434
435
436

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

437
438
439
440
	data[dofMap[v1]] = v2;
      }
    }
		        
441
  protected:
Thomas Witkowski's avatar
Thomas Witkowski committed
442
    ///
443
    std::vector<ProblemVec*> probStat;
Thomas Witkowski's avatar
Thomas Witkowski committed
444

445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
    /// 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;

461
462
463
    /// Finite element space of the problem.
    FiniteElemSpace *feSpace;

464
465
466
    /// Mesh of the problem.
    Mesh *mesh;

467
468
469
470
471
472
473
    /** \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;

474
475
476
    /// Info level.
    int info;

477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
    /// 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;

    /** \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;    
494
   
495
    /// Number of DOFs in the rank mesh.
496
    int nRankDofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
497

498
    /// Number of DOFs in the whole domain.
499
500
    int nOverallDofs;

Thomas Witkowski's avatar
Thomas Witkowski committed
501
    /** \brief 
Thomas Witkowski's avatar
Thomas Witkowski committed
502
503
504
505
506
507
508
509
510
511
512
513
     * 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
514
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
515
    InteriorBoundary otherIntBoundary;
Thomas Witkowski's avatar
Thomas Witkowski committed
516

517
    /** \brief
518
519
     * Defines the periodic boundaries with other ranks. Periodic boundaries have
     * no owner, as it is the case of interior boundaries.
520
521
522
     */
    InteriorBoundary periodicBoundary;

523
524
525
526
    /** \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
527
    RankToDofContainer sendDofs;
528
529

    /** \brief
530
531
532
     * 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.
533
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
534
    RankToDofContainer recvDofs;
535
536

    /// Maps local to global dof indices.
537
    DofMapping mapLocalGlobalDofs;
538

Thomas Witkowski's avatar
Thomas Witkowski committed
539
    /// Maps local dof indices to real dof indices.
540
    DofMapping mapLocalDofIndex;  
541
542
543
544
545
546

    /** \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.
     */
547
548
    DofIndexToBool isRankDof;

549
    /** \brief
550
551
552
553
     * If periodic boundaries are used, this map stores, for each periodic boundary
     * type, for all DOFs in rank's partition (that are on periodic boundaries), the 
     * corresponding mapped periodic DOFs. The mapping is defined by using global 
     * dof indices.
554
     */
555
    PeriodicDofMap periodicDof;
556
557
558
559
560
561
562
563
    
    /** \brief
     * If periodic boundaries are used, this map stores to each periodic DOF in rank's
     * partition the set of periodic boundaries the DOF is associated to. In 2D, most
     * DOFs are only on one periodic boundary. Only, e.g., in a box with all boundaries
     * being periodic, the for corners are associated by two different boundaries.     
     */
    std::map<int, std::set<BoundaryType> > periodicDofAssociations;
564

565
    /// 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
566
    int rstart;
567

568
569
570
571
572
573
574
    /** \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;
575

576
577
578
    /// Denotes whether there exists a filewriter for this object.
    bool writeSerializationFile;

579
580
581
    /// If true, it is possible to repartition the mesh during computations.
    bool repartitioningAllowed;

582
583
584
585
586
    /** \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;
587

588
589
590
591
592
    /// 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;

593
594
    std::map<int, std::vector<int> > macroElementNeighbours;

595
    friend class ParallelDebug;
596
597
598
  };
}

599
#endif // AMDIS_MESHDISTRIBUTOR_H