FFmmAlgorithmThread.hpp 17.4 KB
Newer Older
1
// ===================================================================================
2
// Copyright ScalFmm 2011 INRIA, Olivier Coulaud, Berenger Bramas, Matthias Messner
3
4
5
6
7
8
9
10
11
12
13
14
// olivier.coulaud@inria.fr, berenger.bramas@inria.fr
// This software is a computer program whose purpose is to compute the FMM.
//
// This software is governed by the CeCILL-C and LGPL licenses and
// abiding by the rules of distribution of free software.  
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public and CeCILL-C Licenses for more details.
// "http://www.cecill.info". 
// "http://www.gnu.org/licenses".
15
// ===================================================================================
16
17
#ifndef FFMMALGORITHMTHREAD_HPP
#define FFMMALGORITHMTHREAD_HPP
18

19

BRAMAS Berenger's avatar
BRAMAS Berenger committed
20
#include "../Utils/FAssert.hpp"
BRAMAS Berenger's avatar
BRAMAS Berenger committed
21
#include "../Utils/FLog.hpp"
22

23
24
25
26
27
#include "../Utils/FTic.hpp"
#include "../Utils/FGlobal.hpp"

#include "../Containers/FOctree.hpp"

28
#include "FCoreCommon.hpp"
29
30
31
32
33
34
35
36
37
38
39
40
41
42

#include <omp.h>

/**
* @author Berenger Bramas (berenger.bramas@inria.fr)
* @class FFmmAlgorithmThread
* @brief
* Please read the license
*
* This class is a threaded FMM algorithm
* It just iterates on a tree and call the kernels with good arguments.
* It used the inspector-executor model :
* iterates on the tree and builds an array to work in parallel on this array
*
COULAUD Olivier's avatar
COULAUD Olivier committed
43
* Of course this class does not deallocate pointer given in arguments.
44
*
berenger-bramas's avatar
berenger-bramas committed
45
* When using this algorithm the P2P is thread safe.
46
*/
47
template<class OctreeClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass>
BRAMAS Berenger's avatar
BRAMAS Berenger committed
48
class FFmmAlgorithmThread : public FAbstractAlgorithm{
berenger-bramas's avatar
berenger-bramas committed
49
50
    OctreeClass* const tree;                  //< The octree to work on
    KernelClass** kernels;                    //< The kernels
51

berenger-bramas's avatar
berenger-bramas committed
52
    typename OctreeClass::Iterator* iterArray;
53
    int leafsNumber;
54
55

    static const int SizeShape = 3*3*3;
berenger-bramas's avatar
berenger-bramas committed
56
57
58
    int shapeLeaf[SizeShape];    

    const int MaxThreads;
59

60
61
    const int OctreeHeight;

62
63
64
65
66
67
public:
    /** The constructor need the octree and the kernels used for computation
      * @param inTree the octree to work on
      * @param inKernels the kernels to call
      * An assert is launched if one of the arguments is null
      */
berenger-bramas's avatar
berenger-bramas committed
68
    FFmmAlgorithmThread(OctreeClass* const inTree, KernelClass* const inKernels)
69
        : tree(inTree) , kernels(nullptr), iterArray(nullptr), leafsNumber(0),
70
          MaxThreads(omp_get_max_threads()), OctreeHeight(tree->getHeight()) {
71

BRAMAS Berenger's avatar
BRAMAS Berenger committed
72
        FAssertLF(tree, "tree cannot be null");
73

berenger-bramas's avatar
berenger-bramas committed
74
        this->kernels = new KernelClass*[MaxThreads];
75
        #pragma omp parallel for schedule(static)
berenger-bramas's avatar
berenger-bramas committed
76
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
berenger-bramas's avatar
berenger-bramas committed
77
            this->kernels[idxThread] = new KernelClass(*inKernels);
78
79
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
80
        FLOG(FLog::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
81
82
83
84
    }

    /** Default destructor */
    virtual ~FFmmAlgorithmThread(){
berenger-bramas's avatar
berenger-bramas committed
85
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
86
87
            delete this->kernels[idxThread];
        }
berenger-bramas's avatar
berenger-bramas committed
88
        delete [] this->kernels;
89
90
91
92
93
94
    }

    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
95
    void execute(const unsigned operationsToProceed = FFmmNearAndFarFields){
96
97
98
99
100
101

        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            this->shapeLeaf[idxShape] = 0;
        }

        // Count leaf
102
        leafsNumber = 0;
berenger-bramas's avatar
berenger-bramas committed
103
        typename OctreeClass::Iterator octreeIterator(tree);
104
105
        octreeIterator.gotoBottomLeft();
        do{
106
            ++leafsNumber;
107
            const FTreeCoordinate& coord = octreeIterator.getCurrentCell()->getCoordinate();
108
109
110
            ++this->shapeLeaf[(coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3)];

        } while(octreeIterator.moveRight());
berenger-bramas's avatar
berenger-bramas committed
111
        iterArray = new typename OctreeClass::Iterator[leafsNumber];
BRAMAS Berenger's avatar
BRAMAS Berenger committed
112
        FAssertLF(iterArray, "iterArray bad alloc");
113

114
        if(operationsToProceed & FFmmP2M) bottomPass();
115

116
        if(operationsToProceed & FFmmM2M) upwardPass();
117

118
        if(operationsToProceed & FFmmM2L) transferPass();
119

120
        if(operationsToProceed & FFmmL2L) downardPass();
121

122
        if((operationsToProceed & FFmmP2P) || (operationsToProceed & FFmmL2P)) directPass((operationsToProceed & FFmmP2P),(operationsToProceed & FFmmL2P));
123
124

        delete [] iterArray;
125
        iterArray = nullptr;
126
127
    }

128
private:
berenger-bramas's avatar
berenger-bramas committed
129
130
131
132
    /////////////////////////////////////////////////////////////////////////////
    // P2M
    /////////////////////////////////////////////////////////////////////////////

133
134
    /** P2M */
    void bottomPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
135
        FLOG( FLog::Controller.write("\tStart Bottom Pass\n").write(FLog::Flush) );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
136
        FLOG(FTic counterTime);
137

berenger-bramas's avatar
berenger-bramas committed
138
        typename OctreeClass::Iterator octreeIterator(tree);
139
140
141
142
143
144
145
146
        int leafs = 0;
        // Iterate on leafs
        octreeIterator.gotoBottomLeft();
        do{
            iterArray[leafs] = octreeIterator;
            ++leafs;
        } while(octreeIterator.moveRight());

147
148
        const int chunkSize = FMath::Max(1 , leafs/(omp_get_max_threads()*omp_get_max_threads()));

BRAMAS Berenger's avatar
BRAMAS Berenger committed
149
        FLOG(FTic computationCounter);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
150
        #pragma omp parallel
151
        {
berenger-bramas's avatar
berenger-bramas committed
152
            KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
153
            #pragma omp for nowait schedule(dynamic, chunkSize)
154
155
156
157
158
159
            for(int idxLeafs = 0 ; idxLeafs < leafs ; ++idxLeafs){
                // We need the current cell that represent the leaf
                // and the list of particles
                myThreadkernels->P2M( iterArray[idxLeafs].getCurrentCell() , iterArray[idxLeafs].getCurrentListSrc());
            }
        }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
160
        FLOG(computationCounter.tac() );
161

BRAMAS Berenger's avatar
BRAMAS Berenger committed
162
163
        FLOG( FLog::Controller << "\tFinished (@Bottom Pass (P2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.elapsed() << " s\n" );
164

165
166
    }

berenger-bramas's avatar
berenger-bramas committed
167
168
169
170
    /////////////////////////////////////////////////////////////////////////////
    // Upward
    /////////////////////////////////////////////////////////////////////////////

171
172
    /** M2M */
    void upwardPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
173
        FLOG( FLog::Controller.write("\tStart Upward Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
174
175
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
176
177

        // Start from leal level - 1
berenger-bramas's avatar
berenger-bramas committed
178
        typename OctreeClass::Iterator octreeIterator(tree);
179
180
        octreeIterator.gotoBottomLeft();
        octreeIterator.moveUp();
berenger-bramas's avatar
berenger-bramas committed
181
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
182
183
184

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
185
            FLOG(FTic counterTimeLevel);
186
            int numberOfCells = 0;
187
188
            // for each cells
            do{
189
190
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
191
192
193
194
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

195
196
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));

BRAMAS Berenger's avatar
BRAMAS Berenger committed
197
            FLOG(computationCounter.tic());
198
            #pragma omp parallel
199
            {
berenger-bramas's avatar
berenger-bramas committed
200
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
201
                #pragma omp for nowait  schedule(dynamic, chunkSize)
202
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
203
204
                    // We need the current cell and the child
                    // child is an array (of 8 child) that may be null
205
                    myThreadkernels->M2M( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
206
207
                }
            }
berenger-bramas's avatar
berenger-bramas committed
208

BRAMAS Berenger's avatar
BRAMAS Berenger committed
209
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
210
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
211
212
        }

berenger-bramas's avatar
berenger-bramas committed
213

BRAMAS Berenger's avatar
BRAMAS Berenger committed
214
215
        FLOG( FLog::Controller << "\tFinished (@Upward Pass (M2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
216

217
218
    }

berenger-bramas's avatar
berenger-bramas committed
219
    /////////////////////////////////////////////////////////////////////////////
220
    // Transfer
berenger-bramas's avatar
berenger-bramas committed
221
222
    /////////////////////////////////////////////////////////////////////////////

223
    /** M2L L2L */
224
    void transferPass(){
225

BRAMAS Berenger's avatar
BRAMAS Berenger committed
226
        FLOG( FLog::Controller.write("\tStart Downward Pass (M2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
227
228
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
berenger-bramas's avatar
berenger-bramas committed
229

230
231
232
233
234
235
        typename OctreeClass::Iterator octreeIterator(tree);
        octreeIterator.moveDown();
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        // for each levels
        for(int idxLevel = 2 ; idxLevel < OctreeHeight ; ++idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
236
            FLOG(FTic counterTimeLevel);
237
238
239
240
241
242
243
244
245
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

246
247
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));

BRAMAS Berenger's avatar
BRAMAS Berenger committed
248
            FLOG(computationCounter.tic());
249
            #pragma omp parallel
250
251
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
252
                const CellClass* neighbors[343];
253

254
                #pragma omp for  schedule(dynamic, chunkSize) nowait
255
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
256
                    const int counter = tree->getInteractionNeighbors(neighbors,  iterArray[idxCell].getCurrentGlobalCoordinate(),idxLevel);
257
                    if(counter) myThreadkernels->M2L( iterArray[idxCell].getCurrentCell() , neighbors, counter, idxLevel);
258
                }
259
260

                myThreadkernels->finishedLevelM2L(idxLevel);
261
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
262
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
263
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
264
265
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
266
267
        FLOG( FLog::Controller << "\tFinished (@Downward Pass (M2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
268
    }
berenger-bramas's avatar
berenger-bramas committed
269

270
    /////////////////////////////////////////////////////////////////////////////
COULAUD Olivier's avatar
COULAUD Olivier committed
271
    // Downward
272
273
274
275
    /////////////////////////////////////////////////////////////////////////////

    void downardPass(){ // second L2L

BRAMAS Berenger's avatar
BRAMAS Berenger committed
276
        FLOG( FLog::Controller.write("\tStart Downward Pass (L2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
277
278
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
279
280
281
282
283
284
285

        typename OctreeClass::Iterator octreeIterator(tree);
        octreeIterator.moveDown();

        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        const int heightMinusOne = OctreeHeight - 1;
COULAUD Olivier's avatar
COULAUD Olivier committed
286
        // for each levels excepted leaf level
287
        for(int idxLevel = 2 ; idxLevel < heightMinusOne ; ++idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
288
            FLOG(FTic counterTimeLevel);
289
290
291
292
293
294
295
296
297
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

BRAMAS Berenger's avatar
BRAMAS Berenger committed
298
            FLOG(computationCounter.tic());
299
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));
300
            #pragma omp parallel
301
302
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
303
                #pragma omp for nowait schedule(dynamic, chunkSize)
304
305
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                    myThreadkernels->L2L( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
306
307
                }
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
308
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
309
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
310
311
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
312
313
        FLOG( FLog::Controller << "\tFinished (@Downward Pass (L2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
314
315
    }

316
317


berenger-bramas's avatar
berenger-bramas committed
318
319
320
321
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

322
    /** P2P */
323
    void directPass(const bool p2pEnabled, const bool l2pEnabled){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
324
        FLOG( FLog::Controller.write("\tStart Direct Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
325
326
327
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
        FLOG(FTic computationCounterP2P);
328

329
        omp_lock_t lockShape[SizeShape];
330
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
331
            omp_init_lock(&lockShape[idxShape]);
332
333
        }

334
335
336
        struct LeafData{
            MortonIndex index;
            CellClass* cell;
berenger-bramas's avatar
berenger-bramas committed
337
338
            ContainerClass* targets;
            ContainerClass* sources;
339
340
341
        };
        LeafData* const leafsDataArray = new LeafData[this->leafsNumber];

342
        const int LeafIndex = OctreeHeight - 1;
343
344
345
346
347
348
349

        int startPosAtShape[SizeShape];
        startPosAtShape[0] = 0;
        for(int idxShape = 1 ; idxShape < SizeShape ; ++idxShape){
            startPosAtShape[idxShape] = startPosAtShape[idxShape-1] + this->shapeLeaf[idxShape-1];
        }

350
        #pragma omp parallel
351
        {
352

353
354
355
            const float step = float(this->leafsNumber) / float(omp_get_num_threads());
            const int start = int(FMath::Ceil(step * float(omp_get_thread_num())));
            const int tempEnd = int(FMath::Ceil(step * float(omp_get_thread_num()+1)));
356
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
357

berenger-bramas's avatar
berenger-bramas committed
358
            typename OctreeClass::Iterator octreeIterator(tree);
359
            octreeIterator.gotoBottomLeft();
360
361
362
363
364

            for(int idxPreLeaf = 0 ; idxPreLeaf < start ; ++idxPreLeaf){
                octreeIterator.moveRight();
            }

365
            // for each leafs
366
            for(int idxMyLeafs = start ; idxMyLeafs < end ; ++idxMyLeafs){
367
                //iterArray[leafs] = octreeIterator;
368
                //++leafs;
369
                const FTreeCoordinate& coord = octreeIterator.getCurrentGlobalCoordinate();
370
                const int shapePosition = (coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3);
371

372
373
374
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
375

COULAUD Olivier's avatar
COULAUD Olivier committed
376
377
                leafsDataArray[positionToWork].index   = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell    = octreeIterator.getCurrentCell();
378
379
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
380

381
382
                octreeIterator.moveRight();
            }
383

384
            #pragma omp barrier
385

BRAMAS Berenger's avatar
BRAMAS Berenger committed
386
            FLOG(if(!omp_get_thread_num()) computationCounter.tic());
387

berenger-bramas's avatar
berenger-bramas committed
388
            KernelClass& myThreadkernels = (*kernels[omp_get_thread_num()]);
389
            // There is a maximum of 26 neighbors
berenger-bramas's avatar
berenger-bramas committed
390
            ContainerClass* neighbors[27];
391
            int previous = 0;
392
393

            for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
394
                const int endAtThisShape = this->shapeLeaf[idxShape] + previous;
395
396
                const int chunkSize = FMath::Max(1 , endAtThisShape/(omp_get_num_threads()*omp_get_num_threads()));
                #pragma omp for schedule(dynamic, chunkSize)
397
398
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
399
400
401
402
403
404
405
406
407
408
409
                    if(l2pEnabled){
                        myThreadkernels.L2P(currentIter.cell, currentIter.targets);
                    }
                    if(p2pEnabled){
                        // need the current particles and neighbors particles
                        FLOG(if(!omp_get_thread_num()) computationCounterP2P.tic());
                        const int counter = tree->getLeafsNeighbors(neighbors, currentIter.cell->getCoordinate(), LeafIndex);
                        myThreadkernels.P2P(currentIter.cell->getCoordinate(), currentIter.targets,
                                            currentIter.sources, neighbors, counter);
                        FLOG(if(!omp_get_thread_num()) computationCounterP2P.tac());
                    }
410
                }
411
412

                previous = endAtThisShape;
413
414
            }
        }
415

BRAMAS Berenger's avatar
BRAMAS Berenger committed
416
        FLOG(computationCounter.tac());
417

418
        delete [] leafsDataArray;
419
420
421
422
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

423

BRAMAS Berenger's avatar
BRAMAS Berenger committed
424
        FLOG( FLog::Controller << "\tFinished (@Direct Pass (L2P + P2P) = "  << counterTime.tacAndElapsed() << "s)\n" );
COULAUD Olivier's avatar
COULAUD Olivier committed
425
426
        FLOG( FLog::Controller << "\t\t Computation L2P + P2P : " << computationCounter.cumulated()    << " s\n" );
        FLOG( FLog::Controller << "\t\t Computation P2P :       " << computationCounterP2P.cumulated() << " s\n" );
427

428
429
430
431
432
433
434
    }

};


#endif //FFMMALGORITHMTHREAD_HPP

435