MeshDistributor.h 34.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/******************************************************************************
 *
 * AMDiS - Adaptive multidimensional simulations
 *
 * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.
 * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis
 *
 * Authors: 
 * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *
 * This file is part of AMDiS
 *
 * See also license.opensource.txt in the distribution.
 * 
 ******************************************************************************/
20
21


22

23
/** \file MeshDistributor.h */
24

25
26
#ifndef AMDIS_MESHDISTRIBUTOR_H
#define AMDIS_MESHDISTRIBUTOR_H
27
28


Thomas Witkowski's avatar
Thomas Witkowski committed
29
#include <mpi.h>
30
#include "parallel/DofComm.h"
31
#include "parallel/ElementObjectDatabase.h"
32
#include "parallel/ParallelTypes.h"
33
#include "parallel/MeshLevelData.h"
34
#include "parallel/MeshPartitioner.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
35
#include "parallel/InteriorBoundary.h"
36
#include "parallel/ParallelDofMapping.h"
37
#include "parallel/PeriodicMap.h"
38
#include "parallel/StdMpi.h"
39
#include "AMDiS_fwd.h"
40
#include "Containers.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
41
#include "Global.h"
42
43
#include "ProblemTimeInterface.h"
#include "ProblemIterationInterface.h"
44
#include "FiniteElemSpace.h"
45
#include "Serializer.h"
Thomas Witkowski's avatar
Thomas Witkowski committed
46
#include "BoundaryManager.h"
47
48
49
#include <string>

#include "operations/functors.hpp"
50

51
namespace AMDiS { namespace Parallel {
52

Thomas Witkowski's avatar
Thomas Witkowski committed
53
54
55

  struct BoundaryDofInfo
  {
56
    std::map<GeoIndex, DofContainerSet> geoDofs;
Thomas Witkowski's avatar
Thomas Witkowski committed
57
58
  };

59

60
  class MeshDistributor
61
  {
62
  private:
63
    MeshDistributor();
64
65
	          
  public:
Thomas Witkowski's avatar
Thomas Witkowski committed
66
67
    ~MeshDistributor();

68
    /// Initialization of mesh distributor.
69
    void initParallelization();
70

71
    /// Clean up procedure for the mesh distributor and attached objects.
72
    void exitParallelization();
73

74
75
76
77
78
79
80
81
    /** \brief
     * Register a parallel DOF mapping. This DOF mapping object will than 
     * automatically updated by the mesh distributer after mesh changes.
     *
     * \param[in]  dofMap   Parallel DOF mapping object.
     */
    void registerDofMap(ParallelDofMapping &dofMap);

Thomas Witkowski's avatar
Thomas Witkowski committed
82
83
84
85
86
87
88
    /** \brief
     * Removes a registered DOF mapping from the mesh distributor.
     *
     * \param[in] dofMap   Parallel DOF mapping object to be removed.
     */
    void removeDofMap(ParallelDofMapping &dofMap);

89
90
91
    /// Adds a DOFVector to the set of \ref interchangeVecs. Thus, this vector 
    /// will be automatically interchanged between ranks when mesh is 
    /// repartitioned.
92
93
    template< typename T >
    void addInterchangeVector(DOFVector<T> *vec) {}
94
95
96
97
98
    void addInterchangeVector(DOFVector<double> *vec)
    {
      interchangeVectors.push_back(vec);
    }

99
100
101
102
103
104
105
106
107
108
109
110
    /// Removes the pointer to DOFVector @param vec from the
    /// set of interchange vectors.
    template< typename T >
    void removeInterchangeVector(DOFVector<T> *vec) {}
    void removeInterchangeVector(DOFVector< double >* vec)
    {
      std::vector< DOFVector< double >* >::iterator it;
      it = std::find(interchangeVectors.begin(), interchangeVectors.end(), vec);
      if ( it != interchangeVectors.end())
        interchangeVectors.erase(it);
    }

111
    /// Adds all DOFVectors of a SystemVector to \ref interchangeVecs.
112
    void addInterchangeVector(SystemVector *vec);
113
114
115

    /// The same as for DOFVectors
    void removeInterchangeVector(SystemVector* vec);
116
    
117
    /** \brief
118
     * This function checks if the mesh has changed on at least one rank. In 
119
120
121
122
     * 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.
123
     *
124
125
126
127
128
     * \param[in]  tryRepartition   If this parameter is true, repartitioning 
     *                              may be done. This depends on several other 
     *                              parameters. If the parameter is false, the 
     *                              mesh is only checked and adapted but never 
     *                              repartitioned.
129
     */
130
    void checkMeshChange(bool tryRepartition = true);
131

Thomas Witkowski's avatar
Thomas Witkowski committed
132
133
134
    /// 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.
Siqi Ling's avatar
Siqi Ling committed
135
    bool repartitionMesh();
136
    
137
    
Thomas Witkowski's avatar
Thomas Witkowski committed
138
139
140
141
142
143
144
    void getImbalanceFactor(double &imbalance, 
			    int &minDofs, 
			    int &maxDofs,
			    int &sumDofs);

    double getImbalanceFactor();

145
146
147
    /// Calculates the imbalancing factor and prints it to screen.
    void printImbalanceFactor();

Thomas Witkowski's avatar
Thomas Witkowski committed
148
149
150
151
    /// 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.
152
    void testForMacroMesh();
153

154
    inline std::string getName() 
155
156
157
    { 
      return name; 
    }
158

159
160
161
162
163
164
    inline Mesh* getMacroMesh()
    {
      return macroMesh;
    }
    
    inline Mesh* getMesh(int i = 0)
Thomas Witkowski's avatar
Thomas Witkowski committed
165
    {
166
167
168
169
170
171
      return meshes[i];
    }
    
    inline int getNumberOfMeshes()
    {
      return meshes.size();
Thomas Witkowski's avatar
Thomas Witkowski committed
172
173
    }

174
175
    /// Returns the periodic mapping handler, \ref periodicMap.
    inline PeriodicMap& getPeriodicMap()
176
    {
177
      return periodicMap;
178
    }
179

180
181
182
183
//     DofComm& getDofComm(int level)
//     {
//       return dofComm[level];
//     }
184
185
186
187
188
189
190
191
192
193
    
    DofComm& getDofComm(Mesh* mesh, int level)
    {
      return dofComms[mesh][level];
    }
    
    std::map<Mesh*, MultiLevelDofComm>& getDofComms()
    {
      return dofComms;
    }
194

195
    InteriorBoundary& getIntBoundary(int level)
196
    {
197
      return intBoundary[level];
198
    }
199
200
201
202
203
    
    std::map<int, int>& getPartitionMap()
    {
      return partitionMap;
    }
204

205
    inline long getLastMeshChangeIndex()
206
    {
207
208
209
210
211
212
213
214
215
216
      int overallMeshChangeIndex = 0;
      for(size_t i = 0; i < meshes.size(); i++) {
	overallMeshChangeIndex += lastMeshChangeIndexs[meshes[i]];
      }
      return overallMeshChangeIndex;
    }
    
    inline long getLastMeshChangeIndex(Mesh* m)
    {
      return lastMeshChangeIndexs[m];
217
    }
218

219
    inline int getMpiRank()
220
    {
221
      return mpiRank;
222
    }
223

224
    inline int getMpiSize(int level)
Thomas Witkowski's avatar
Thomas Witkowski committed
225
    {
226
      return levelData.getMpiComm(level).Get_size();
Thomas Witkowski's avatar
Thomas Witkowski committed
227
228
    }

229
    inline MPI::Intracomm& getMpiComm(int level)
230
    {
231
      return levelData.getMpiComm(level);
232
233
    }

234
235
236
237
238
    inline bool isInitialized()
    {
      return initialized;
    }

239
    // Writes all data of this object to an output stream.
240
    void serialize(std::ostream &out);
241

242
    // Reads the object data from an input stream.
243
    void deserialize(std::istream &in);
244
245
246
247
    
    /// Works quite similar to the function \ref synchVector, but instead the 
    /// values of subdomain vectors are combined along the boundaries, by a
    /// binary functor. 
248
    // minorRank => majorRank
249
250
    template<typename T, typename Operator>
    void synchVector(DOFVector<T> &vec, Operator op)
251
    {
252
      const FiniteElemSpace *fe = vec.getFeSpace();
253
      MultiLevelDofComm& dofComm = dofComms[fe->getMesh()];
254

255
256
      int nLevels = levelData.getNumberOfLevels();
      for (int level = nLevels - 1; level >= 0; level--) {
257
	StdMpi<std::vector<T> > stdMpi(levelData.getMpiComm(level));
258

259
	for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe);
260
	     !it.end(); it.nextRank()) {
261
	  std::vector<T> dofs;
262
263
264
265
266
267
268
269
	  dofs.reserve(it.getDofs().size());
	  
	  for (; !it.endDofIter(); it.nextDof())
	    dofs.push_back(vec[it.getDofIndex()]);
	  
	  stdMpi.send(it.getRank(), dofs);
	}
	
270
	for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); 
271
272
	     !it.end(); it.nextRank())
	  stdMpi.recv(it.getRank());
273
	
274
	stdMpi.startCommunication();
275
	
276
	for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); 
277
278
	     !it.end(); it.nextRank())
	  for (; !it.endDofIter(); it.nextDof())
279
280
	    op(vec[it.getDofIndex()],
	       stdMpi.getRecvData(it.getRank())[it.getDofCounter()]);
281
      }
282
      synchVector(vec);
283
284
    }
    
285
    
286
287
288
289
290
291
292
293
294
295
296
297
298
    /** \brief
    * Synchronize \p vec using indicator vector \p additionalVecs, e.g. let
    * additionalVecs[0] be 1 on all dofs the value should be taken from
    my rank
    * and 0 elsewhere.
    */
    // op(std::vector<T>& out, std::vector<T> const& in)
    template<typename T, typename Operator>
    void synchMultiVector(DOFVector<T> &vec, std::vector<DOFVector<T>*> additionalVecs, Operator op)
    {
    // get FE space and check equal FE space
    const FiniteElemSpace *fe = vec.getFeSpace();
    MultiLevelDofComm& dofComm = dofComms[fe->getMesh()];
299

300
301
302
303
    typedef typename std::vector<DOFVector<T>*>::iterator Iterator;

    int nLevels = levelData.getNumberOfLevels();
    for (int level = nLevels - 1; level >= 0; level--)
304
    {
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        StdMpi < std::vector<std::vector<T> > >
        stdMpi(levelData.getMpiComm(level));

        for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe);
        !it.end(); it.nextRank())
        {
        std::vector<std::vector<T> > dofs;
        dofs.reserve(it.getDofs().size());
        for (; !it.endDofIter(); it.nextDof())
        {
        std::vector<T> values;
        values.reserve(additionalVecs.size() + 1);
        values.push_back( vec[it.getDofIndex()] );
        for (Iterator vecIt = additionalVecs.begin(); vecIt !=
    additionalVecs.end(); ++vecIt )
        values.push_back( (**vecIt)[it.getDofIndex()] );
        dofs.push_back( values );
        }
        stdMpi.send(it.getRank(), dofs);
        }
325

326
327
328
        for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe);
        !it.end(); it.nextRank())
        stdMpi.recv(it.getRank());
329

330
        stdMpi.startCommunication();
331

332
333
334
335
336
337
338
339
340
        for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe);
        !it.end(); it.nextRank()) {
        for (; !it.endDofIter(); it.nextDof()) {
    std::vector<T> values;
    values.reserve(additionalVecs.size() + 1);
    values.push_back( vec[it.getDofIndex()] );
    for (Iterator vecIt = additionalVecs.begin(); vecIt !=
        additionalVecs.end(); ++vecIt )
    values.push_back( (**vecIt)[it.getDofIndex()] );
341

342
343
344
345
    op(values, stdMpi.getRecvData(it.getRank())[it.getDofCounter()]);
    }
        }
    }
346

347
348
    synchVector(vec);
    }
349
350
351
352

  
  
    
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
    /** \brief
    * This function must be used if the values of a set of DOFVectors must be
    * synchronized 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
    * boundary, to all other ranks also having these DOFs.
    *
    * The synchronization direction is from major to minor rank. This means
    * that the value of the rank with the higher number sends its value
    * to the rank with the lower number.
    */
    // majorRank => minorRank
    template<typename T>
    void synchVector(std::vector<DOFVector<T>*> &vecs)
    {
      if (vecs.size() > 0)
      {
        // get FE space
        const FiniteElemSpace *fe = vecs[0]->getFeSpace();
        // TODO: check equal FE space
        // The lines below do not work!
        // for ( typename std::vector<DOFVector<T>*>::iterator vecIt = vecs.begin(); vecIt != vecs.end(); ++vecIt)
        //   TEST_EXIT( (*vecIt)->getFeSpace()->getBasisFcts()->getDegree() == fe->getBasisFcts()->getDegree() )("FE space of vectors to synch not equal!\n");

        MultiLevelDofComm& dofComm = dofComms[fe->getMesh()];
        
        int nLevels = levelData.getNumberOfLevels();
        for (int level = nLevels - 1; level >= 0; level--)
        {
          StdMpi<std::vector<std::vector<T> > > stdMpi(levelData.getMpiComm(level));
          
          for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); !it.end(); it.nextRank())
          {
            std::vector<std::vector<T> > dofs;
            dofs.reserve(it.getDofs().size());
            for (; !it.endDofIter(); it.nextDof())
            {
              std::vector<T> values;
              values.reserve(vecs.size());
              for (typename std::vector<DOFVector<T>*>::iterator vecIt = vecs.begin(); vecIt != vecs.end(); ++vecIt )
                values.push_back((**vecIt)[it.getDofIndex()]);
              dofs.push_back(values);
            }
            stdMpi.send(it.getRank(), dofs);
          }

          for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe); !it.end(); it.nextRank())
            stdMpi.recv(it.getRank());

          stdMpi.startCommunication();

          for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe); !it.end(); it.nextRank())
          {
            for (; !it.endDofIter(); it.nextDof())
            {
              std::vector<T> values = stdMpi.getRecvData(it.getRank())[it.getDofCounter()];
              typename std::vector<DOFVector<T>*>::iterator vecIt = vecs.begin();
              typename std::vector<T>::iterator valuesIt = values.begin();
              for (; vecIt != vecs.end(), valuesIt != values.end(); ++vecIt , ++valuesIt)
                (**vecIt)[it.getDofIndex()] = *valuesIt;
            }
          }
        }
      }
    }
    
    /** \brief
    * Works quite similar to the function \ref synchVector with an operator/
    * assigner for the values on the subdomain boundaries of the DOFVector vec.
    * Additionally, the values stored in additionalVecs are synchronized in
    * the same way (direction (minor to major or major to minor rank)) as the
    * DOFs of the variable vec.
    */
    template<typename T, typename Operator>
    void synchVectorSameWay(DOFVector<T> &vec, std::vector<DOFVector<T>*> additionalVecs, Operator op)
    {
      // get FE space and check equal FE space
      const FiniteElemSpace *fe = vec.getFeSpace();
      // TODO: check equal FE space
      // The lines below do not work!
      // for ( typename std::vector<DOFVector<T>*>::iterator vecIt = additionalVecs.begin(); vecIt != additionalVecs.end(); ++vecIt)
      //   TEST_EXIT( (*vecIt)->getFeSpace()->getBasisFcts()->getDegree() == fe->getBasisFcts()->getDegree() )("FE space of vectors to synch not equal!\n");

      MultiLevelDofComm& dofComm = dofComms[fe->getMesh()];

      int nLevels = levelData.getNumberOfLevels();
      for (int level = nLevels - 1; level >= 0; level--)
      {
        StdMpi < std::vector<std::vector<T> > > stdMpi(levelData.getMpiComm(level));

        for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe); !it.end(); it.nextRank())
        {
          std::vector<std::vector<T> > dofs;
          dofs.reserve(it.getDofs().size());
          for (; !it.endDofIter(); it.nextDof())
          {
            std::vector<T> values;
            values.reserve(additionalVecs.size() + 1);
            values.push_back( vec[it.getDofIndex()] );
            for (typename std::vector<DOFVector<T>*>::iterator vecIt = additionalVecs.begin(); vecIt != additionalVecs.end(); ++vecIt )
              values.push_back( (**vecIt)[it.getDofIndex()] );
            dofs.push_back( values );
          }
          stdMpi.send(it.getRank(), dofs);
        }

        for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); !it.end(); it.nextRank())
          stdMpi.recv(it.getRank());

        stdMpi.startCommunication();

        for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); !it.end(); it.nextRank())
        {
          for (; !it.endDofIter(); it.nextDof())
          {
            DegreeOfFreedom idx = it.getDofIndex();
            std::vector<T> values = stdMpi.getRecvData(it.getRank())[it.getDofCounter()];

            T minorRankValue = vec[idx];
            T majorRankValue = values[0];
            op(vec[idx], values[0]);
            T synchValue = vec[idx];

            TEST_EXIT(additionalVecs.size() == values.size()-1)("The number of additional vectors and the received values do not match!\n");

            typename std::vector<DOFVector<T>*>::iterator vecIt = additionalVecs.begin();
            typename std::vector<T>::iterator valuesIt = values.begin();
            ++valuesIt; // exclude the first one since it belongs to the variable vec
            for (; vecIt != additionalVecs.end(), valuesIt != values.end(); ++vecIt , ++valuesIt)
              if (synchValue == majorRankValue)
                (**vecIt)[idx] = *valuesIt;
          }
        }
      }
      // call simple sync method
      std::vector<DOFVector<T>*> allDOFVectors;
      allDOFVectors.push_back(&vec);
      for ( int i = 0; i < additionalVecs.size(); ++i )
        allDOFVectors.push_back(additionalVecs[i]);
      synchVector(allDOFVectors);
    }
    
494
495
496
497
498
499
500
501
502
503
    /** \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 
     * boundary, to all other ranks also having these DOFs.
     *
     * This function must be used, for example, after the linear system is
     * solved, or after the DOFVector is set by some user defined functions, 
     * e.g., initial solution functions.
     */    
504
     // majorRank => minorRank
505
506
507
    template<typename T>
    void synchVector(DOFVector<T> &vec) 
    {
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
      const FiniteElemSpace *fe = vec.getFeSpace();
      MultiLevelDofComm& dofComm = dofComms[fe->getMesh()];

      int nLevels = levelData.getNumberOfLevels();
      for (int level = nLevels - 1; level >= 0; level--) {
	StdMpi<std::vector<T> > stdMpi(levelData.getMpiComm(level));

	for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); 
	     !it.end(); it.nextRank()) {

	  std::vector<T> dofs;
	  dofs.reserve(it.getDofs().size());
	  
	  for (; !it.endDofIter(); it.nextDof())
	    dofs.push_back(vec[it.getDofIndex()]);
	  
	  stdMpi.send(it.getRank(), dofs);
	}
	
527
	for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe); 
528
529
530
531
532
533
534
535
536
537
538
	     !it.end(); it.nextRank())
	  stdMpi.recv(it.getRank());
	
	stdMpi.startCommunication();
	
	for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe); 
	     !it.end(); it.nextRank())
	  for (; !it.endDofIter(); it.nextDof())
	    vec[it.getDofIndex()] = 
	      stdMpi.getRecvData(it.getRank())[it.getDofCounter()];
      }
539
    }
Thomas Witkowski's avatar
Thomas Witkowski committed
540
   
Thomas Witkowski's avatar
Blub  
Thomas Witkowski committed
541
542
543
    /// 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.
544
    void synchVector(SystemVector &vec);
545
    
546
547
    /// Works quite similar to the function \ref synchVector, but instead the 
    /// values of subdomain vectors are add along the boundaries.
548
    // minorRank => majorRank
Thomas Witkowski's avatar
Thomas Witkowski committed
549
550
551
    template<typename T>
    void synchAddVector(DOFVector<T> &vec)
    {
552
      const FiniteElemSpace *fe = vec.getFeSpace();
553
      MultiLevelDofComm& dofComm = dofComms[fe->getMesh()];
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

      int nLevels = levelData.getNumberOfLevels();
      for (int level = nLevels - 1; level >= 0; level--) {
	StdMpi<std::vector<T> > stdMpi(levelData.getMpiComm(level));

	for (DofComm::Iterator it(dofComm[level].getRecvDofs(), fe);
	     !it.end(); it.nextRank()) {
	  std::vector<T> dofs;
	  dofs.reserve(it.getDofs().size());
	  
	  for (; !it.endDofIter(); it.nextDof())
	    dofs.push_back(vec[it.getDofIndex()]);
	  
	  stdMpi.send(it.getRank(), dofs);
	}
	
570
	for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); 
571
572
573
574
575
576
577
578
579
580
581
582
583
	     !it.end(); it.nextRank())
	  stdMpi.recv(it.getRank());
	
	stdMpi.startCommunication();
	
	for (DofComm::Iterator it(dofComm[level].getSendDofs(), fe); 
	     !it.end(); it.nextRank())
	  for (; !it.endDofIter(); it.nextDof())
	    vec[it.getDofIndex()] += 
	      stdMpi.getRecvData(it.getRank())[it.getDofCounter()];
      }

      synchVector(vec);
Thomas Witkowski's avatar
Thomas Witkowski committed
584
585
    }

586
587
588
589
590
591
    /// In 3D, a subdomain may not be a valid AMDiS mesh if it contains two
    /// parts which are only connected by an edge. In this case, the standard
    /// refinement algorithm does not work correctly, as two elements connected
    /// only on one edge are not neighours by definition. This functions checks
    /// for this situation and fix the problem. For this, the mesh is search for
    /// all edges connecting two elements that are otherwise not connected.
592
593
594
595
596
597
598
599
600
601
602
603
604
    void fix3dMeshRefinement();

    /** \brief Is used only within \ref fix3dMeshRefinement.
     * 
     * \param[in]  elems            Set of macro element indices.
     * \param[out] disconnectedEls  On output, this vector contains sets of
     *                              element indices. The union is equal to elems.
     *                              Each set contains all element indices, which
     *                              are reachable among each other by neighbour
     *                              relations. Elements within two different sets
     *                              cannot be reached via neigbourhood relation.
     */
    void helpToFix(std::set<int> &elems, 
605
		   std::vector<std::set<int> > &disconnectedEls);
606

Thomas Witkowski's avatar
Thomas Witkowski committed
607
608
    void setBoundaryDofRequirement(Flag flag)
    {
609
      createBoundaryDofFlag |= flag;
Thomas Witkowski's avatar
Thomas Witkowski committed
610
611
    }

612
613
    BoundaryDofInfo& getBoundaryDofInfo(const FiniteElemSpace *feSpace,
					int level)
614
    {
615
616
617
618
619
620
621
      FUNCNAME("MeshDistributor::getBoundaryDofInfo()");

      TEST_EXIT_DBG(level < static_cast<int>(boundaryDofInfo.size()))
	("Wrong level number: %d, whereas array size is %d!\n", 
	 level, boundaryDofInfo.size());

      return boundaryDofInfo[level][feSpace];
622
623
    }

624
625
    void getAllBoundaryDofs(const FiniteElemSpace *feSpace, 
			    int level,
626
			    DofContainer& dofs);
627

Thomas Witkowski's avatar
Thomas Witkowski committed
628
    ElementObjectDatabase& getElementObjectDb() 
629
630
631
    {
      return elObjDb;
    }
632
633
634

    /// Adds a stationary problem to the global mesh distributor objects.
    static void addProblemStatGlobal(ProblemStatSeq *probStat);
Thomas Witkowski's avatar
Thomas Witkowski committed
635
636
637
638
639

    MeshLevelData& getMeshLevelData() 
    {
      return levelData;
    }
640
641
642
643
644
645
646
647
    
    /// Update dof communicators, boundary dof info and the parallel dof mappings.
    /// If it is called for all meshes, \ref updateLocalGlobalNumbering is automatically
    /// called inside. If it is used for each mesh seperately, please don't forget to 
    /// add \ref updateLocalGlobalNumbering to update the global matrix index.
    void updateDofRelatedStruct();
    
    void updateDofRelatedStruct(Mesh* mesh);
Thomas Witkowski's avatar
Thomas Witkowski committed
648

649
    void updateLocalGlobalNumbering();
650
651
652
653
654
655
    
    /// set variable \ref repartitioningAllowed
    void setRepartitioningAllowed(bool allowed)
    {
      repartitioningAllowed = allowed;
    }
Siqi Ling's avatar
Siqi Ling committed
656
657
658
659
660
    
    void setElementWeights(std::map<int, double>& elWgts)
    {
      elemWeights = elWgts;
    }
661

662
  protected:
663
664
665
666
667
668
669
670
671
672
673
674
    /// Rebuild only part of the mesh domain, which is necessary
    void quickRepartition(Mesh* mesh);
    
    /// Rebuild whole mesh domain
    void fullRepartition(Mesh* mesh);
    
    /// Updates all registered parallel DOF mappings, see \ref dofMaps.
    void updateDofsToDofMapping(Mesh* mesh = NULL);

    /// Updates the DOF after the mesh has been changed, see \ref dofMaps.
    void updateDofsToDofMapping(ParallelDofMapping &dmap,
				    const FiniteElemSpace *feSpace);
675
676
677
678
    
    /// Checks if repartition is needed.
    bool isRepartitionNecessary();
    
679
    /// Creates an initial partitioning of the mesh.
Thomas Witkowski's avatar
Thomas Witkowski committed
680
681
682
683
684
    void createInitialPartitioning();

    /// Set for each element on the partitioning level the number of 
    /// leaf elements.
    void setInitialElementWeights();
685
686
687
688
    
    /// Calculates \ref elemWeights with the gloabl max weight and 
    /// global sum of weight.
    void calculateElemWeights();
Thomas Witkowski's avatar
Thomas Witkowski committed
689
690

    ///
691
692
    void addProblemStat(ProblemStatSeq *probStat);

693
694
    /// Determines the interior boundaries, i.e. boundaries between ranks, and
    /// stores all information about them in \ref interiorBoundary.
695
    void createInteriorBoundary(bool firstCall);
Thomas Witkowski's avatar
Thomas Witkowski committed
696

Thomas Witkowski's avatar
Thomas Witkowski committed
697
    ///
698
    void createBoundaryDofs(Mesh* mesh = NULL);
Thomas Witkowski's avatar
Thomas Witkowski committed
699

700
701
    /// Removes all macro elements from the mesh that are not part of ranks 
    /// partition.
702
703
    void removeMacroElements();

704
705
706
707
    /// Calls \ref createPeriodicMap(feSpace) for all FE spaces that are
    /// handled by the mesh distributor.
    void createPeriodicMap();

708
709
710
    /// Creates, for a specific FE space, 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 periodicDofMap.  
711
    void createPeriodicMap(const FiniteElemSpace *feSpace);
712

713
714
715
716
717
718
    /// This function is called only once during the initialization when the
    /// whole macro mesh is available on all cores. It copies the pointers of all
    /// macro elements to \ref allMacroElements and stores all neighbour 
    /// information based on macro element indices (and not pointer based) in 
    /// \ref macroElementNeighbours. These information are then used to 
    /// reconstruct macro elements during mesh redistribution.
719
720
    void createMacroElementInfo();

721
722
    void updateMacroElementInfo();

723
    /** \brief
724
725
726
727
728
729
     * 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.
730
     *
731
732
     * \param[in] allBound   Defines a map from rank to interior boundaries 
     *                       which should be checked.
733
     * \param[in] mesh       The mesh the interior boundaries belong to.
734
     *
735
736
737
     * \return    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.
738
     */
739
    bool checkAndAdaptBoundary(RankToBoundMap &allBound, Mesh* mesh);
740
  
741
742
743
744
    /// Removes all periodic boundary condition information from all matrices and
    /// vectors of all stationary problems and from the mesh itself.
    void removePeriodicBoundaryConditions();

745
746
747
748
    /// Removes all periodic boundary condition information from all matrices and
    /// vector of a given stationary problem.
    void removePeriodicBoundaryConditions(ProblemStatSeq *probStat);

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

752
753
    void createMeshLevelStructure();

754
    /// Writes a vector of dof pointers to an output stream.
755
    void serialize(std::ostream &out, DofContainer &data);
756

757
    /// Writes a \ref RankToDofContainer to an output stream.
758
759
    void serialize(std::ostream &out, 
		   std::map<int, std::map<const FiniteElemSpace*, DofContainer> > &data);
760

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

    /// Reads a \ref RankToDofContainer from an input stream.
766
767
768
    void deserialize(std::istream &in, 
		     std::map<int, std::map<const FiniteElemSpace*, DofContainer> > &data,
		     std::map<const FiniteElemSpace*, std::map<int, const DegreeOfFreedom*> > &dofIndexMap);
769
770
771

    /// Writes a mapping from dof pointers to some values to an output stream.
    template<typename T>
772
    void serialize(std::ostream &out, std::map<const DegreeOfFreedom*, T> &data)
773
    {
774
775
      FUNCNAME("ParallelDomainBase::serialize()");

776
      int mapSize = data.size();
777
      SerUtil::serialize(out, mapSize);
778
      for (typename std::map<const DegreeOfFreedom*, T>::iterator it = data.begin();
779
780
781
	   it != data.end(); ++it) {
	int v1 = (*(it->first));
	T v2 = it->second;
782
783
	SerUtil::serialize(out, v1);
	SerUtil::serialize(out, v2);
784
785
786
787
788
      }
    }

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

794
      int mapSize = 0;
795
      SerUtil::deserialize(in, mapSize);
796
797
798
      for (int i = 0; i < mapSize; i++) {
	int v1 = 0;
	T v2;
799
800
	SerUtil::deserialize(in, v1);
	SerUtil::deserialize(in, v2);
801

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

805
	data[dofIndexMap[v1]] = v2;
806
807
      }
    }
808

809
  protected:
810
811
    /// List of all stationary problems that are managed by this mesh 
    /// distributor.
812
    std::vector<ProblemStatSeq*> problemStat;
Thomas Witkowski's avatar
Thomas Witkowski committed
813

814
815
816
    /// If true, the mesh distributor is already initialized;
    bool initialized;

817
818
819
820
    /// The rank of the current process.
    int mpiRank;

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

823
    /// Set of all different FE spaces.
824
    std::vector<const FiniteElemSpace*> feSpaces;
825
    
826
827
828
829
830
831
832
833
834
835
    /// Always equal to meshes[0] which is used as macro
    /// mesh. For example, passed to \ref meshPartitioner.
    Mesh *macroMesh;
    
    /// Meshes to be managed for parallelization. Currently only two meshes
    /// are allowed since multi mesh method is limited to two meshes.
    std::vector<Mesh*> meshes;
    
    /// Stores the map of meshes and the corresponding FE spaces defined on them
    MeshToFeSpaces meshToFeSpaces;
836

837
838
839
    /// 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.    
840
841
    RefinementManager *refineManager;

842
843
    /// Pointer to a mesh partitioner that is used to partition the mesh to 
    /// the ranks.
844
    MeshPartitioner *partitioner;
845

846
847
848
849
850
851
    /// Pointer to a mesh partitioner that is used for the very first 
    /// partitioning of the mesh. In most cases, this pointer points to the
    /// same object as \ref partitioner, but this must not be the case in
    /// general.
    MeshPartitioner *initialPartitioner;

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

856
857
    /// Stores to every macro element index the number of the rank that owns this
    /// macro element.
858
    std::map<int, int> partitionMap;
859

860
    /// Database to store and query all sub-objects of all elements of the 
861
    /// macro mesh.
862
    ElementObjectDatabase elObjDb;
Thomas Witkowski's avatar
Thomas Witkowski committed
863

864
    /// Defines the interior boundaries of the domain that result from 
865
    /// partitioning the whole mesh. 
866
    MultiLevelInteriorBoundary intBoundary;
867
868
869
    
    /// Dof communicator objects for each mesh
    std::map<Mesh*, MultiLevelDofComm> dofComms;
870

871
    PeriodicMap periodicMap;
872

873
874
    /// This set of values must be interchanged between ranks when the mesh is 
    /// repartitioned.
875
    std::vector<DOFVector<double>*> interchangeVectors;
876
		        
877
878
879
880
    /// 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.
881
    bool deserialized;
882

883
884
885
    /// Denotes whether there exists a filewriter for this object.
    bool writeSerializationFile;

886
887
    /// If true, it is possible to repartition the mesh during computations.
    bool repartitioningAllowed;
888
889
890
    
    /// repartition the mesh (only) the first time repartitionMesh() is called
    bool repartitionOnlyOnce;
891

892
    /// Stores the number of mesh changes that must lie in between two 
893
    /// repartitionings.
894
895
    int repartitionIthChange;

896
897
898
    ///
    int repartitioningWaitAfterFail;

899
900
    /// Counts the number of mesh changes after the last mesh repartitioning 
    /// was done.
901
    int nMeshChangesAfterLastRepartitioning;
902

903
904
905
    /// Countes the number of mesh repartitions that were done. Till now, this 
    /// variable is used only for debug outputs.
    int repartitioningCounter;
906

907
908
909
910
911
    /// If repartitioning of the mesh fail, this variable has a positive value
    /// that gives the number of mesh changes the mesh distributer will wait
    /// before trying new mesh repartitioning.
    int repartitioningFailed;

912
    /// Directory name where all debug output files should be written to.
913
    std::string debugOutputDir;
914

915
916
    /// Stores the mesh change index. This is used to recognize changes in the
    /// mesh structure (e.g. through refinement or coarsening managers).
917
    std::map<Mesh*, long> lastMeshChangeIndexs;
918

919
920
921
922
    /// Stores for all macro elements of the original macro mesh the
    /// neighbourhood information based on element indices. Thus, each macro
    /// element index is mapped to a vector containing all indices of 
    /// neighbouring macro elements.
923
    std::map<int, std::vector<int> > macroElementNeighbours;
924

925
926
    /// Store all macro elements of the overall mesh, i.e., before the
    /// mesh is redistributed for the first time.
927
928
929
    /// Store all macro elements of the overall mesh, i.e., before the
    /// mesh is redistributed for the first time.   
    std::map<Mesh*, std::vector<MacroElement*> > allMacroElements;
930

Thomas Witkowski's avatar
Thomas Witkowski committed
931
932
    Flag createBoundaryDofFlag;

933
934
    /// Stores on each mesh level for all FE spaces the information about
    /// all boundary DOFs.
935
    std::vector<std::map<const FiniteElemSpace*, BoundaryDofInfo> > boundaryDofInfo;
936

937
938
    /// Stores information about hierarchical decomposition of the mesh levels.
    /// Is used to specify multi level solver methods.
939
940
    MeshLevelData levelData;

Thomas Witkowski's avatar
bla  
Thomas Witkowski committed
941
942
943
944
945
946
    /// If there is no mesh adaptivity, the mesh distributor can remove some
    /// data structures which are only used if mesh changes or it must be
    /// redistributed due to some local adaptivity. By default, this variable
    /// is set to true, and thus no special assumption are made.
    bool meshAdaptivity;

947
948
949
950
951
    /// Specifies whether the global domain has periodic boundaries. Thus, this
    /// variable is not related to rank's subdomain but to the global problem
    /// and therefore the value if the same on all ranks.
    bool hasPeriodicBoundary;

952
953
    /// Set of all parallel DOF mapping object that are registered by parallel
    /// solver objects and must be updated automatically after mesh change.
954
    std::vector<ParallelDofMapping*> dofMaps;
955

Thomas Witkowski's avatar
Thomas Witkowski committed
956
957
958
    /// If true, detailed timings for benchmarking are printed.
    bool printTimings;

959
960
961
    /// If true, detailed information about memory usage are printed.
    bool printMemoryUsage;

Thomas Witkowski's avatar
Thomas Witkowski committed
962
  public:
963
964
965
    /// The boundary DOFs are sorted by subobject entities, i.e., first all
    /// face DOFs, edge DOFs and to the last vertex DOFs will be set to
    /// communication structure vectors, \ref sendDofs and \ref recvDofs.
Thomas Witkowski's avatar
Thomas Witkowski committed
966
967
    static const Flag BOUNDARY_SUBOBJ_SORTED;

968
969
970
971
972
973
974
975
976
    /// When boundary DOFs are created, \ref boundaryDofInfo is filled for
    /// all DOFs that this rank will send to other ranks (thus, rank 
    /// owned DOFs.
    static const Flag BOUNDARY_FILL_INFO_SEND_DOFS;

    /// When boundary DOFs are created, \ref boundaryDofInfo is filled for
    /// all DOFs that this rank will receive from other ranks (thus, DOFs
    /// that are owned by another rank).
    static const Flag BOUNDARY_FILL_INFO_RECV_DOFS;
Thomas Witkowski's avatar
Thomas Witkowski committed
977

978
979
    static MeshDistributor *globalMeshDistributor;

980
    friend class ParallelDebug;
981

982
  };
983
} }
984

985
#endif // AMDIS_MESHDISTRIBUTOR_H