MeshDistributor.h 19.7 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

  using namespace std;
45
  
46
47
  class ParMetisPartitioner;

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

    /// Defines a mapping type from DOFs to a set of rank numbers.
55
    typedef map<const DegreeOfFreedom*, std::set<int> > DofToPartitions;
Thomas Witkowski's avatar
Thomas Witkowski committed
56
57

    /// Defines a mapping type from rank numbers to sets of DOFs.
58
    typedef map<int, DofContainer> RankToDofContainer;
Thomas Witkowski's avatar
Thomas Witkowski committed
59
60

    /// Defines a mapping type from DOF indices to DOF indices.
61
    typedef map<DegreeOfFreedom, DegreeOfFreedom> DofMapping;
Thomas Witkowski's avatar
Thomas Witkowski committed
62

63
    /// Defines a mapping type from DOFs to boolean values.
64
    typedef map<const DegreeOfFreedom*, bool> DofToBool;
65

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

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

72
    typedef map<const DegreeOfFreedom*, DegreeOfFreedom> DofIndexMap;
Thomas Witkowski's avatar
Thomas Witkowski committed
73

74
75
    /// Mapps a boundar type, i.e., a boundary identifier index, to a periodic 
    /// dof mapping.
76
77
78
    typedef map<BoundaryType, DofMapping> PeriodicDofMap;

    typedef vector<MeshStructure> MeshCodeVec;
79

80
  public:
81
    MeshDistributor(string str);
82
83
		          
    virtual ~MeshDistributor() {}
84

85
    void initParallelization();
86

87
    void exitParallelization();
88
89

    void addProblemStat(ProblemVec *probVec);
90

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

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

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

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

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

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

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

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

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

      return periodicDof[type][globalDofIndex];
    }

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

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

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

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

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

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

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

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

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

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

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

215
    // Reads the object data from an input stream.
216
    void deserialize(istream &in);
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

    /** \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);

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

Thomas Witkowski's avatar
Thomas Witkowski committed
244
245
246
247
248
    void updateInteriorBoundaryInfo();

    void createMeshElementData();

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

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

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

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

263
264
    void createMacroElementInfo();

265
266
    void updateMacroElementInfo();

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

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.
     */
293
    void writePartitioningMesh(string filename);
294

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

298
299
300
301
    /// 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
302
    // Removes all periodic boundaries from a given boundary map.
303
    void removePeriodicBoundaryConditions(BoundaryIndexMap& boundaryMap);
Thomas Witkowski's avatar
Thomas Witkowski committed
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
341
342
    /** \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.
     */
343
    bool fitElementToMeshCode(MeshStructure &code, 
344
			      TraverseStack &stack,
345
			      GeoIndex subObj,
346
			      int ithObj,
347
			      bool reverseMode);
348

349
    /// Writes a vector of dof pointers to an output stream.
350
    void serialize(ostream &out, DofContainer &data);
351
352

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

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

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

363
    /// Writes a periodic dof mapping to an output stream.
364
    void serialize(ostream &out, PeriodicDofMap &data);
365

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

368
    /// Reads a periodic dof mapping from an input stream.
369
    void deserialize(istream &in, PeriodicDofMap &data);
370

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

373
374
    /// Writes a mapping from dof pointers to some values to an output stream.
    template<typename T>
375
    void serialize(ostream &out, map<const DegreeOfFreedom*, T> &data)
376
    {
377
378
      FUNCNAME("ParallelDomainBase::serialize()");

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

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

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

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

407
408
409
	data[dofMap[v1]] = v2;
      }
    }
410
411

  public:
412
    vector<DOFVector<double>* > testVec;
413
		        
414
  protected:
Thomas Witkowski's avatar
Thomas Witkowski committed
415
    ///
416
    vector<ProblemVec*> probStat;
Thomas Witkowski's avatar
Thomas Witkowski committed
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)
432
    string name;
433

434
435
436
    /// Finite element space of the problem.
    FiniteElemSpace *feSpace;

437
438
439
    /// Mesh of the problem.
    Mesh *mesh;

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

447
448
449
    /// Info level.
    int info;

450
451
452
453
    /// 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.
454
    map<int, double> elemWeights;
455
456

    /** \brief
457
458
     * Stores to every macro element index the number of the rank that owns this
     * macro element.
459
     */
460
    map<int, int> partitionVec;
461
462

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

471
    /// Number of DOFs in the whole domain.
472
473
    int nOverallDofs;

Thomas Witkowski's avatar
Thomas Witkowski committed
474
475
476
477
    // 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.
478
    map<int, Element*> macroElIndexMap;
Thomas Witkowski's avatar
Thomas Witkowski committed
479
480
    
    // Maps to each macro element index the type of this element.
481
    map<int, int> macroElIndexTypeMap;
Thomas Witkowski's avatar
Thomas Witkowski committed
482

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

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

505
506
507
508
    /** \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
509
    RankToDofContainer sendDofs;
510
511

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

    /// Maps local to global dof indices.
519
    DofMapping mapLocalGlobalDofs;
520

Thomas Witkowski's avatar
Thomas Witkowski committed
521
    /// Maps local dof indices to real dof indices.
522
    DofMapping mapLocalDofIndex;  
523
524
525
526
527
528

    /** \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.
     */
529
530
    DofIndexToBool isRankDof;

531
    /** \brief
532
533
534
535
     * 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.
536
     */
537
    PeriodicDofMap periodicDof;
538
539
540
541
542
543
544
    
    /** \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.     
     */
545
    map<int, std::set<BoundaryType> > periodicDofAssociations;
546

547
    /// 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
548
    int rstart;
549

550
551
552
553
554
555
556
    /** \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;
557

558
559
560
    /// Denotes whether there exists a filewriter for this object.
    bool writeSerializationFile;

561
562
563
    /// If true, it is possible to repartition the mesh during computations.
    bool repartitioningAllowed;

564
565
    int repartitionIthChange;

566
567
    int nTimestepsAfterLastRepartitioning;

568
569
    int repartCounter;

570
    /// Directory name where all debug output files should be written to.
571
    string debugOutputDir;
572

573
574
575
576
577
    /** \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;
578

579
    map<int, vector<int> > macroElementNeighbours;
580

581
582
    /// Store all macro elements of the overall mesh, i.e., before the macro mesh is
    /// redistributed for the first time.
583
    vector<MacroElement*> allMacroElements;
584

585
    friend class ParallelDebug;
586
587
588
  };
}

589
#endif // AMDIS_MESHDISTRIBUTOR_H