MeshDistributor.h 20.2 KB
Newer Older
1
2
3
4
// ============================================================================
// ==                                                                        ==
// == AMDiS - Adaptive multidimensional simulations                          ==
// ==                                                                        ==
5
// ==  http://www.amdis-fem.org                                              ==
6
7
// ==                                                                        ==
// ============================================================================
8
9
10
11
12
13
14
15
16
17
18
19
//
// Software License for AMDiS
//
// Copyright (c) 2010 Dresden University of Technology 
// All rights reserved.
// Authors: Simon Vey, Thomas Witkowski et al.
//
// This file is part of AMDiS
//
// See also license.opensource.txt in the distribution.


20

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

23
24
#ifndef AMDIS_MESHDISTRIBUTOR_H
#define AMDIS_MESHDISTRIBUTOR_H
25
26
27


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

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

42
namespace AMDiS {
43
  
44
45
  class ParMetisPartitioner;

46
  class MeshDistributor
47
  {
48
  protected:
Thomas Witkowski's avatar
Thomas Witkowski committed
49
50
51
52
53
54
55
56
57
58
59
60
    /// 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;

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

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

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

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

72
73
74
    /// Mapps a boundar type, i.e., a boundary identifier index, to a periodic 
    /// dof mapping.
    typedef std::map<BoundaryType, DofMapping> PeriodicDofMap;
75
76
    
    typedef std::vector<MeshStructure> MeshCodeVec;
77

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

83
    void initParallelization();
84

85
    void exitParallelization();
86
87

    void addProblemStat(ProblemVec *probVec);
88

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

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

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

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

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

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

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

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

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

      return periodicDof[type][globalDofIndex];
    }

153
154
155
    /// 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)
156
    {      
157
      return periodicDofAssociations[globalDofIndex];
158
    }
159

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

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

173
174
    /// 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.
175
176
177
178
    inline bool getIsRankDof(DegreeOfFreedom dof)
    {
      return isRankDof[dof];
    }
179

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

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

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

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

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

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

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

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

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

Thomas Witkowski's avatar
Thomas Witkowski committed
242
243
244
245
246
    void updateInteriorBoundaryInfo();

    void createMeshElementData();

    void createBoundaryData();
Thomas Witkowski's avatar
Thomas Witkowski committed
247

248
249
250
    /// Removes all macro elements from the mesh that are not part of ranks partition.
    void removeMacroElements();

251
    /// Updates the local and global DOF numbering after the mesh has been changed.
252
    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
    void updateMacroElementInfo();

265
266
267
268
269
270
271
272
273
274
275
276
277
    /** \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);
278
279
280
281
282
283
284
285
  
    /** \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();

286
287
288
289
290
291
292
    /** \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);

293
294
295
    /// Sets \ref isRankDof to all matrices and rhs vectors in all stationary problems.
    void setRankDofs();

296
297
298
299
    /// 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
300
    // Removes all periodic boundaries from a given boundary map.
301
    void removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap);
Thomas Witkowski's avatar
Thomas Witkowski committed
302

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
    /** \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.
     */
341
    bool fitElementToMeshCode(MeshStructure &code, 
342
			      TraverseStack &stack,
343
			      GeoIndex subObj,
344
			      int ithObj,
345
			      bool reverseMode);
346

347
348
349
350
351
352
353
354
355
356
357
358
359
    /// 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);
360

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

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

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

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

371
372
373
374
    /// 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)
    {
375
376
      FUNCNAME("ParallelDomainBase::serialize()");

377
      int mapSize = data.size();
378
      SerUtil::serialize(out, mapSize);
379
380
381
382
      for (typename std::map<const DegreeOfFreedom*, T>::iterator it = data.begin();
	   it != data.end(); ++it) {
	int v1 = (*(it->first));
	T v2 = it->second;
383
384
	SerUtil::serialize(out, v1);
	SerUtil::serialize(out, v2);
385
386
387
388
389
390
391
392
      }
    }

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

395
      int mapSize = 0;
396
      SerUtil::deserialize(in, mapSize);
397
398
399
      for (int i = 0; i < mapSize; i++) {
	int v1 = 0;
	T v2;
400
401
	SerUtil::deserialize(in, v1);
	SerUtil::deserialize(in, v2);
402
403
404

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

405
406
407
	data[dofMap[v1]] = v2;
      }
    }
408
409

  public:
410
    std::vector<DOFVector<double>* > testVec;
411
		        
412
  protected:
Thomas Witkowski's avatar
Thomas Witkowski committed
413
    ///
414
    std::vector<ProblemVec*> probStat;
Thomas Witkowski's avatar
Thomas Witkowski committed
415

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
    /// 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;

432
433
434
    /// Finite element space of the problem.
    FiniteElemSpace *feSpace;

435
436
437
    /// Mesh of the problem.
    Mesh *mesh;

438
439
440
441
442
443
444
    /** \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;

445
446
447
    /// Info level.
    int info;

448
449
450
451
452
453
454
    /// 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
455
456
     * Stores to every macro element index the number of the rank that owns this
     * macro element.
457
458
459
460
     */
    std::map<int, int> partitionVec;

    /** \brief
461
462
     * Stores an old partitioning of elements. To every macro element index the
     * number of the rank it corresponds to is stored.
463
464
     */
    std::map<int, int> oldPartitionVec;    
465
   
466
    /// Number of DOFs in the rank mesh.
467
    int nRankDofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
468

469
    /// Number of DOFs in the whole domain.
470
471
    int nOverallDofs;

Thomas Witkowski's avatar
Thomas Witkowski committed
472
473
474
475
476
477
478
479
480
481
    // Data structure to store all sub-objects of all elements of the macro mesh.
    ElementObjects elObjects;

    // Maps to each macro element index a pointer to the corresponding element.
    std::map<int, Element*> macroElIndexMap;
    
    // Maps to each macro element index the type of this element.
    std::map<int, int> macroElIndexTypeMap;

    // The following three data structures store periodic DOFs, edges and faces.
482
    std::map<std::pair<DegreeOfFreedom, DegreeOfFreedom>, BoundaryType> periodicVertices;
Thomas Witkowski's avatar
Thomas Witkowski committed
483
484
485
    std::map<std::pair<DofEdge, DofEdge>, BoundaryType> periodicEdges;
    std::map<std::pair<DofFace, DofFace>, BoundaryType> periodicFaces;

Thomas Witkowski's avatar
Thomas Witkowski committed
486
    /** \brief 
Thomas Witkowski's avatar
Thomas Witkowski committed
487
488
489
490
491
492
493
494
495
496
497
498
     * 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
499
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
500
    InteriorBoundary otherIntBoundary;
Thomas Witkowski's avatar
Thomas Witkowski committed
501

502
    /** \brief
503
504
     * Defines the periodic boundaries with other ranks. Periodic boundaries have
     * no owner, as it is the case of interior boundaries.
505
506
507
     */
    InteriorBoundary periodicBoundary;

508
509
510
511
    /** \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
512
    RankToDofContainer sendDofs;
513
514

    /** \brief
515
516
517
     * 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.
518
     */
Thomas Witkowski's avatar
Thomas Witkowski committed
519
    RankToDofContainer recvDofs;
520
521

    /// Maps local to global dof indices.
522
    DofMapping mapLocalGlobalDofs;
523

Thomas Witkowski's avatar
Thomas Witkowski committed
524
    /// Maps local dof indices to real dof indices.
525
    DofMapping mapLocalDofIndex;  
526
527
528
529
530
531

    /** \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.
     */
532
533
    DofIndexToBool isRankDof;

534
    /** \brief
535
536
537
538
     * 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.
539
     */
540
    PeriodicDofMap periodicDof;
541
542
543
544
545
546
547
548
    
    /** \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;
549

550
    /// 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
551
    int rstart;
552

553
554
555
556
557
558
559
    /** \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;
560

561
562
563
    /// Denotes whether there exists a filewriter for this object.
    bool writeSerializationFile;

564
565
566
    /// If true, it is possible to repartition the mesh during computations.
    bool repartitioningAllowed;

567
568
    int repartitionIthChange;

569
570
    int nTimestepsAfterLastRepartitioning;

571
572
    int repartCounter;

573
574
575
    /// Directory name where all debug output files should be written to.
    std::string debugOutputDir;

576
577
578
579
580
    /** \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;
581

582
583
    std::map<int, std::vector<int> > macroElementNeighbours;

584
585
586
587
    /// Store all macro elements of the overall mesh, i.e., before the macro mesh is
    /// redistributed for the first time.
    std::vector<MacroElement*> allMacroElements;

588
    friend class ParallelDebug;
589
590
591
  };
}

592
#endif // AMDIS_MESHDISTRIBUTOR_H