FFmmAlgorithmThread.hpp 17.8 KB
Newer Older
1
// ===================================================================================
2
// Copyright ScalFmm 2011 INRIA, Olivier Coulaud, Berenger Bramas, Matthias Messner
3 4 5 6
// 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
7 8
// abiding by the rules of distribution of free software.
//
9 10 11 12
// 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.
13
// "http://www.cecill.info".
14
// "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
#include "../Utils/FTic.hpp"
#include "../Utils/FGlobal.hpp"
25
#include "Utils/FAlgorithmTimers.hpp"
26 27 28

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

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

#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
44
* Of course this class does not deallocate pointer given in arguments.
45
*
berenger-bramas's avatar
berenger-bramas committed
46
* When using this algorithm the P2P is thread safe.
47
*/
48
template<class OctreeClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass>
49
class FFmmAlgorithmThread : public FAbstractAlgorithm, public FAlgorithmTimers{
berenger-bramas's avatar
berenger-bramas committed
50 51
    OctreeClass* const tree;                  //< The octree to work on
    KernelClass** kernels;                    //< The kernels
52

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

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

    const int MaxThreads;
60

61 62
    const int OctreeHeight;

63 64 65 66 67 68
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
69
    FFmmAlgorithmThread(OctreeClass* const inTree, KernelClass* const inKernels)
70
        : tree(inTree) , kernels(nullptr), iterArray(nullptr), leafsNumber(0),
71
          MaxThreads(omp_get_max_threads()), OctreeHeight(tree->getHeight()) {
72

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

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

BRAMAS Berenger's avatar
BRAMAS Berenger committed
84
        FLOG(FLog::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
85 86 87 88
    }

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

95
protected:
96 97 98 99
    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
100
    void executeCore(const unsigned operationsToProceed) override {
101 102 103 104 105 106

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

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

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

119
        Timers[P2MTimer].tic();
120
        if(operationsToProceed & FFmmP2M) bottomPass();
121
        Timers[P2MTimer].tac();
122

123
        Timers[M2MTimer].tic();
124
        if(operationsToProceed & FFmmM2M) upwardPass();
125
        Timers[M2MTimer].tac();
126

127
        Timers[M2LTimer].tic();
128
        if(operationsToProceed & FFmmM2L) transferPass();
129
        Timers[M2LTimer].tac();
130

131
        Timers[L2LTimer].tic();
132
        if(operationsToProceed & FFmmL2L) downardPass();
133
        Timers[L2LTimer].tac();
134

135 136 137
        Timers[NearTimer].tic();
        if( (operationsToProceed & FFmmP2P) || (operationsToProceed & FFmmL2P) ) directPass((operationsToProceed & FFmmP2P),(operationsToProceed & FFmmL2P));
        Timers[NearTimer].tac();
138 139

        delete [] iterArray;
140
        iterArray = nullptr;
141 142
    }

berenger-bramas's avatar
berenger-bramas committed
143 144 145 146
    /////////////////////////////////////////////////////////////////////////////
    // P2M
    /////////////////////////////////////////////////////////////////////////////

147 148
    /** P2M */
    void bottomPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
149
        FLOG( FLog::Controller.write("\tStart Bottom Pass\n").write(FLog::Flush) );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
150
        FLOG(FTic counterTime);
151

berenger-bramas's avatar
berenger-bramas committed
152
        typename OctreeClass::Iterator octreeIterator(tree);
153 154 155 156 157 158 159 160
        int leafs = 0;
        // Iterate on leafs
        octreeIterator.gotoBottomLeft();
        do{
            iterArray[leafs] = octreeIterator;
            ++leafs;
        } while(octreeIterator.moveRight());

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

BRAMAS Berenger's avatar
BRAMAS Berenger committed
163
        FLOG(FTic computationCounter);
BRAMAS Berenger's avatar
BRAMAS Berenger committed
164
        #pragma omp parallel
165
        {
berenger-bramas's avatar
berenger-bramas committed
166
            KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
167
            #pragma omp for nowait schedule(dynamic, chunkSize)
168 169 170 171 172 173
            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
174
        FLOG(computationCounter.tac() );
175

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

179 180
    }

berenger-bramas's avatar
berenger-bramas committed
181 182 183 184
    /////////////////////////////////////////////////////////////////////////////
    // Upward
    /////////////////////////////////////////////////////////////////////////////

185 186
    /** M2M */
    void upwardPass(){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
187
        FLOG( FLog::Controller.write("\tStart Upward Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
188 189
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
190 191

        // Start from leal level - 1
berenger-bramas's avatar
berenger-bramas committed
192
        typename OctreeClass::Iterator octreeIterator(tree);
193 194
        octreeIterator.gotoBottomLeft();
        octreeIterator.moveUp();
berenger-bramas's avatar
berenger-bramas committed
195
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
196 197 198

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
199
            FLOG(FTic counterTimeLevel);
200
            int numberOfCells = 0;
201 202
            // for each cells
            do{
203 204
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
205 206 207 208
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

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

BRAMAS Berenger's avatar
BRAMAS Berenger committed
211
            FLOG(computationCounter.tic());
212
            #pragma omp parallel
213
            {
berenger-bramas's avatar
berenger-bramas committed
214
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
215
                #pragma omp for nowait  schedule(dynamic, chunkSize)
216
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
217 218
                    // We need the current cell and the child
                    // child is an array (of 8 child) that may be null
219
                    myThreadkernels->M2M( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
220 221
                }
            }
berenger-bramas's avatar
berenger-bramas committed
222

BRAMAS Berenger's avatar
BRAMAS Berenger committed
223
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
224
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
225 226
        }

berenger-bramas's avatar
berenger-bramas committed
227

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

231 232
    }

berenger-bramas's avatar
berenger-bramas committed
233
    /////////////////////////////////////////////////////////////////////////////
234
    // Transfer
berenger-bramas's avatar
berenger-bramas committed
235 236
    /////////////////////////////////////////////////////////////////////////////

237
    /** M2L L2L */
238
    void transferPass(){
239

BRAMAS Berenger's avatar
BRAMAS Berenger committed
240
        FLOG( FLog::Controller.write("\tStart Downward Pass (M2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
241 242
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
berenger-bramas's avatar
berenger-bramas committed
243

244 245 246 247 248 249
        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
250
            FLOG(FTic counterTimeLevel);
251 252 253 254 255 256 257 258 259
            int numberOfCells = 0;
            // for each cells
            do{
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveDown();
            octreeIterator = avoidGotoLeftIterator;

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

BRAMAS Berenger's avatar
BRAMAS Berenger committed
262
            FLOG(computationCounter.tic());
263
            #pragma omp parallel
264 265
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
266
                const CellClass* neighbors[343];
267

268
                #pragma omp for  schedule(dynamic, chunkSize) nowait
269
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
270
                    const int counter = tree->getInteractionNeighbors(neighbors,  iterArray[idxCell].getCurrentGlobalCoordinate(),idxLevel);
271
                    if(counter) myThreadkernels->M2L( iterArray[idxCell].getCurrentCell() , neighbors, counter, idxLevel);
272
                }
273 274

                myThreadkernels->finishedLevelM2L(idxLevel);
275
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
276
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
277
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
278 279
        }

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

284
    /////////////////////////////////////////////////////////////////////////////
COULAUD Olivier's avatar
COULAUD Olivier committed
285
    // Downward
286 287 288 289
    /////////////////////////////////////////////////////////////////////////////

    void downardPass(){ // second L2L

BRAMAS Berenger's avatar
BRAMAS Berenger committed
290
        FLOG( FLog::Controller.write("\tStart Downward Pass (L2L)\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
291 292
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
293 294 295 296 297 298 299

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

        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);

        const int heightMinusOne = OctreeHeight - 1;
COULAUD Olivier's avatar
COULAUD Olivier committed
300
        // for each levels excepted leaf level
301
        for(int idxLevel = 2 ; idxLevel < heightMinusOne ; ++idxLevel ){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
302
            FLOG(FTic counterTimeLevel);
303 304 305 306 307 308 309 310 311
            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
312
            FLOG(computationCounter.tic());
313
            const int chunkSize = FMath::Max(1 , numberOfCells/(omp_get_max_threads()*omp_get_max_threads()));
314
            #pragma omp parallel
315 316
            {
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
317
                #pragma omp for nowait schedule(dynamic, chunkSize)
318 319
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                    myThreadkernels->L2L( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
320 321
                }
            }
BRAMAS Berenger's avatar
BRAMAS Berenger committed
322
            FLOG(computationCounter.tac());
BRAMAS Berenger's avatar
BRAMAS Berenger committed
323
            FLOG( FLog::Controller << "\t\t>> Level " << idxLevel << " = "  << counterTimeLevel.tacAndElapsed() << "s\n" );
324 325
        }

BRAMAS Berenger's avatar
BRAMAS Berenger committed
326 327
        FLOG( FLog::Controller << "\tFinished (@Downward Pass (L2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FLOG( FLog::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
328 329
    }

330 331


berenger-bramas's avatar
berenger-bramas committed
332 333 334 335
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

336
    /** P2P */
337
    void directPass(const bool p2pEnabled, const bool l2pEnabled){
BRAMAS Berenger's avatar
BRAMAS Berenger committed
338
        FLOG( FLog::Controller.write("\tStart Direct Pass\n").write(FLog::Flush); );
BRAMAS Berenger's avatar
BRAMAS Berenger committed
339 340 341
        FLOG(FTic counterTime);
        FLOG(FTic computationCounter);
        FLOG(FTic computationCounterP2P);
342

343
        omp_lock_t lockShape[SizeShape];
344
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
345
            omp_init_lock(&lockShape[idxShape]);
346 347
        }

348 349 350
        struct LeafData{
            MortonIndex index;
            CellClass* cell;
berenger-bramas's avatar
berenger-bramas committed
351 352
            ContainerClass* targets;
            ContainerClass* sources;
353 354 355
        };
        LeafData* const leafsDataArray = new LeafData[this->leafsNumber];

356
        const int LeafIndex = OctreeHeight - 1;
357 358 359 360 361 362 363

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

364
        #pragma omp parallel
365
        {
366

367 368 369
            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)));
370
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
371

berenger-bramas's avatar
berenger-bramas committed
372
            typename OctreeClass::Iterator octreeIterator(tree);
373
            octreeIterator.gotoBottomLeft();
374 375 376 377 378

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

379
            // for each leafs
380
            for(int idxMyLeafs = start ; idxMyLeafs < end ; ++idxMyLeafs){
381
                //iterArray[leafs] = octreeIterator;
382
                //++leafs;
383
                const FTreeCoordinate& coord = octreeIterator.getCurrentGlobalCoordinate();
384
                const int shapePosition = (coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3);
385

386 387 388
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
389

COULAUD Olivier's avatar
COULAUD Olivier committed
390 391
                leafsDataArray[positionToWork].index   = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell    = octreeIterator.getCurrentCell();
392 393
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
394

395 396
                octreeIterator.moveRight();
            }
397

398
            #pragma omp barrier
399

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

berenger-bramas's avatar
berenger-bramas committed
402
            KernelClass& myThreadkernels = (*kernels[omp_get_thread_num()]);
403
            // There is a maximum of 26 neighbors
berenger-bramas's avatar
berenger-bramas committed
404
            ContainerClass* neighbors[27];
405
            int previous = 0;
406 407

            for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
408
                const int endAtThisShape = this->shapeLeaf[idxShape] + previous;
409 410
                const int chunkSize = FMath::Max(1 , endAtThisShape/(omp_get_num_threads()*omp_get_num_threads()));
                #pragma omp for schedule(dynamic, chunkSize)
411 412
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
413 414 415 416 417 418 419 420 421 422 423
                    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());
                    }
424
                }
425 426

                previous = endAtThisShape;
427 428
            }
        }
429

BRAMAS Berenger's avatar
BRAMAS Berenger committed
430
        FLOG(computationCounter.tac());
431

432
        delete [] leafsDataArray;
433 434 435 436
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

437

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

442 443 444 445 446 447
    }

};


#endif //FFMMALGORITHMTHREAD_HPP