FFmmAlgorithmThread.hpp 16.3 KB
Newer Older
1
// ===================================================================================
2 3 4 5 6 7 8 9
// Logiciel initial: ScalFmm Version 0.5
// Co-auteurs : Olivier Coulaud, Bérenger Bramas.
// Propriétaires : INRIA.
// Copyright © 2011-2012, diffusé sous les termes et conditions d’une licence propriétaire.
// Initial software: ScalFmm Version 0.5
// Co-authors: Olivier Coulaud, Bérenger Bramas.
// Owners: INRIA.
// Copyright © 2011-2012, spread under the terms and conditions of a proprietary license.
10
// ===================================================================================
11 12
#ifndef FFMMALGORITHMTHREAD_HPP
#define FFMMALGORITHMTHREAD_HPP
13

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

#include "../Utils/FAssertable.hpp"
#include "../Utils/FDebug.hpp"
#include "../Utils/FTrace.hpp"
#include "../Utils/FTic.hpp"
#include "../Utils/FGlobal.hpp"

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


#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
*
* Of course this class does not deallocate pointer given in arguements.
*
berenger-bramas's avatar
berenger-bramas committed
39
* When using this algorithm the P2P is thread safe.
40
*/
berenger-bramas's avatar
berenger-bramas committed
41
template<class OctreeClass, class ParticleClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass>
42
class FFmmAlgorithmThread : protected FAssertable{
berenger-bramas's avatar
berenger-bramas committed
43 44
    OctreeClass* const tree;                  //< The octree to work on
    KernelClass** kernels;                    //< The kernels
45

berenger-bramas's avatar
berenger-bramas committed
46
    typename OctreeClass::Iterator* iterArray;
47
    int leafsNumber;
48 49

    static const int SizeShape = 3*3*3;
berenger-bramas's avatar
berenger-bramas committed
50 51 52
    int shapeLeaf[SizeShape];    

    const int MaxThreads;
53

54 55
    const int OctreeHeight;

56 57 58 59 60 61
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
62
    FFmmAlgorithmThread(OctreeClass* const inTree, KernelClass* const inKernels)
63
                      : tree(inTree) , kernels(0), iterArray(0), leafsNumber(0),
64
                        MaxThreads(omp_get_max_threads()), OctreeHeight(tree->getHeight()) {
65

66
        fassert(tree, "tree cannot be null", __LINE__, __FILE__);
67

berenger-bramas's avatar
berenger-bramas committed
68
        this->kernels = new KernelClass*[MaxThreads];
berenger-bramas's avatar
berenger-bramas committed
69
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
berenger-bramas's avatar
berenger-bramas committed
70
            this->kernels[idxThread] = new KernelClass(*inKernels);
71 72
        }

berenger-bramas's avatar
berenger-bramas committed
73
        FDEBUG(FDebug::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
74 75 76 77
    }

    /** Default destructor */
    virtual ~FFmmAlgorithmThread(){
berenger-bramas's avatar
berenger-bramas committed
78
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
79 80
            delete this->kernels[idxThread];
        }
berenger-bramas's avatar
berenger-bramas committed
81
        delete [] this->kernels;
82 83 84 85 86 87 88
    }

    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
    void execute(){
89
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
90 91 92 93

        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            this->shapeLeaf[idxShape] = 0;
        }
94
        //const int LeafIndex = OctreeHeight - 1;
95 96

        // Count leaf
97
        leafsNumber = 0;
berenger-bramas's avatar
berenger-bramas committed
98
        typename OctreeClass::Iterator octreeIterator(tree);
99 100
        octreeIterator.gotoBottomLeft();
        do{
101
            ++leafsNumber;
102 103 104
            const FTreeCoordinate& coord = octreeIterator.getCurrentCell()->getCoordinate();
            //const MortonIndex index = octreeIterator.getCurrentGlobalIndex();
            //coord.setPositionFromMorton(index, LeafIndex);
105 106 107
            ++this->shapeLeaf[(coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3)];

        } while(octreeIterator.moveRight());
berenger-bramas's avatar
berenger-bramas committed
108
        iterArray = new typename OctreeClass::Iterator[leafsNumber];
109
        fassert(iterArray, "iterArray bad alloc", __LINE__, __FILE__);
110 111 112 113 114 115 116 117 118 119 120

        bottomPass();
        upwardPass();

        downardPass();

        directPass();

        delete [] iterArray;
        iterArray = 0;

121
         
122 123
    }

124
private:
berenger-bramas's avatar
berenger-bramas committed
125 126 127 128
    /////////////////////////////////////////////////////////////////////////////
    // P2M
    /////////////////////////////////////////////////////////////////////////////

129 130
    /** P2M */
    void bottomPass(){
131
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
132
        FDEBUG( FDebug::Controller.write("\tStart Bottom Pass\n").write(FDebug::Flush) );
berenger-bramas's avatar
berenger-bramas committed
133
        FDEBUG(FTic counterTime);
134

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

berenger-bramas's avatar
berenger-bramas committed
144 145
        FDEBUG(FTic computationCounter);
        #pragma omp parallel
146
        {
berenger-bramas's avatar
berenger-bramas committed
147
            KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
berenger-bramas's avatar
berenger-bramas committed
148
            #pragma omp for nowait
149 150 151 152 153 154
            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());
            }
        }
berenger-bramas's avatar
berenger-bramas committed
155
        FDEBUG(computationCounter.tac() );
156

157
        FDEBUG( FDebug::Controller << "\tFinished (@Bottom Pass (P2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
158
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.elapsed() << " s\n" );
159
         
160 161
    }

berenger-bramas's avatar
berenger-bramas committed
162 163 164 165
    /////////////////////////////////////////////////////////////////////////////
    // Upward
    /////////////////////////////////////////////////////////////////////////////

166 167
    /** M2M */
    void upwardPass(){
168
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
169
        FDEBUG( FDebug::Controller.write("\tStart Upward Pass\n").write(FDebug::Flush); );
berenger-bramas's avatar
berenger-bramas committed
170 171
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);
172 173

        // Start from leal level - 1
berenger-bramas's avatar
berenger-bramas committed
174
        typename OctreeClass::Iterator octreeIterator(tree);
175 176
        octreeIterator.gotoBottomLeft();
        octreeIterator.moveUp();
berenger-bramas's avatar
berenger-bramas committed
177
        typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
178 179 180

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
181
            int numberOfCells = 0;
182 183
            // for each cells
            do{
184 185
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
186 187 188 189 190
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

            FDEBUG(computationCounter.tic());
berenger-bramas's avatar
berenger-bramas committed
191
            #pragma omp parallel
192
            {
berenger-bramas's avatar
berenger-bramas committed
193
                KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
194
                #pragma omp for nowait
195
                for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
196 197
                    // We need the current cell and the child
                    // child is an array (of 8 child) that may be null
198
                    myThreadkernels->M2M( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
199 200
                }
            }
berenger-bramas's avatar
berenger-bramas committed
201

202 203 204
            FDEBUG(computationCounter.tac());
        }

berenger-bramas's avatar
berenger-bramas committed
205

206
        FDEBUG( FDebug::Controller << "\tFinished (@Upward Pass (M2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
berenger-bramas's avatar
berenger-bramas committed
207
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
208
         
209 210
    }

berenger-bramas's avatar
berenger-bramas committed
211 212 213 214
    /////////////////////////////////////////////////////////////////////////////
    // Downard
    /////////////////////////////////////////////////////////////////////////////

215 216
    /** M2L L2L */
    void downardPass(){
217
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
218 219

        { // first M2L
berenger-bramas's avatar
berenger-bramas committed
220 221 222 223
            FDEBUG( FDebug::Controller.write("\tStart Downward Pass (M2L)\n").write(FDebug::Flush); );
            FDEBUG(FTic counterTime);
            FDEBUG(FTic computationCounter);

berenger-bramas's avatar
berenger-bramas committed
224
            typename OctreeClass::Iterator octreeIterator(tree);
225
            octreeIterator.moveDown();
berenger-bramas's avatar
berenger-bramas committed
226
            typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
227 228 229

            // for each levels
            for(int idxLevel = 2 ; idxLevel < OctreeHeight ; ++idxLevel ){
230
                int numberOfCells = 0;
231 232
                // for each cells
                do{
233 234
                    iterArray[numberOfCells] = octreeIterator;
                    ++numberOfCells;
235 236 237 238 239
                } while(octreeIterator.moveRight());
                avoidGotoLeftIterator.moveDown();
                octreeIterator = avoidGotoLeftIterator;

                FDEBUG(computationCounter.tic());
berenger-bramas's avatar
berenger-bramas committed
240
                #pragma omp parallel
241
                {
berenger-bramas's avatar
berenger-bramas committed
242
                    KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
243
                    const CellClass* neighbors[189];
244

245
                    #pragma omp for  schedule(dynamic) nowait
246
                    for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
247 248
                        const int counter = tree->getDistantNeighbors(neighbors,  iterArray[idxCell].getCurrentGlobalCoordinate(),idxLevel);
                        if(counter) myThreadkernels->M2L( iterArray[idxCell].getCurrentCell() , neighbors, counter, idxLevel);
249 250 251 252
                    }
                }
                FDEBUG(computationCounter.tac());
            }
berenger-bramas's avatar
berenger-bramas committed
253

254
            FDEBUG( FDebug::Controller << "\tFinished (@Downward Pass (M2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
berenger-bramas's avatar
berenger-bramas committed
255
            FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
256 257 258
        }

        { // second L2L
berenger-bramas's avatar
berenger-bramas committed
259 260 261 262
            FDEBUG( FDebug::Controller.write("\tStart Downward Pass (L2L)\n").write(FDebug::Flush); );
            FDEBUG(FTic counterTime);
            FDEBUG(FTic computationCounter);

berenger-bramas's avatar
berenger-bramas committed
263
            typename OctreeClass::Iterator octreeIterator(tree);
264 265
            octreeIterator.moveDown();

berenger-bramas's avatar
berenger-bramas committed
266
            typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
267 268 269 270

            const int heightMinusOne = OctreeHeight - 1;
            // for each levels exepted leaf level
            for(int idxLevel = 2 ; idxLevel < heightMinusOne ; ++idxLevel ){
271
                int numberOfCells = 0;
272 273
                // for each cells
                do{
274 275
                    iterArray[numberOfCells] = octreeIterator;
                    ++numberOfCells;
276 277 278 279 280
                } while(octreeIterator.moveRight());
                avoidGotoLeftIterator.moveDown();
                octreeIterator = avoidGotoLeftIterator;

                FDEBUG(computationCounter.tic());
berenger-bramas's avatar
berenger-bramas committed
281
                #pragma omp parallel
282
                {
berenger-bramas's avatar
berenger-bramas committed
283
                    KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
284
                    #pragma omp for nowait
285 286
                    for(int idxCell = 0 ; idxCell < numberOfCells ; ++idxCell){
                        myThreadkernels->L2L( iterArray[idxCell].getCurrentCell() , iterArray[idxCell].getCurrentChild(), idxLevel);
287 288 289 290
                    }
                }
                FDEBUG(computationCounter.tac());
            }
berenger-bramas's avatar
berenger-bramas committed
291

292
            FDEBUG( FDebug::Controller << "\tFinished (@Downward Pass (L2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
berenger-bramas's avatar
berenger-bramas committed
293
            FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
294 295
        }

296
         
297 298
    }

berenger-bramas's avatar
berenger-bramas committed
299 300 301 302
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

303 304
    /** P2P */
    void directPass(){
305
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
306
        FDEBUG( FDebug::Controller.write("\tStart Direct Pass\n").write(FDebug::Flush); );
berenger-bramas's avatar
berenger-bramas committed
307 308
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);
309
        FDEBUG(FTic computationCounterP2P);
310

311
        omp_lock_t lockShape[SizeShape];
312
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
313
            omp_init_lock(&lockShape[idxShape]);
314 315
        }

316 317 318
        struct LeafData{
            MortonIndex index;
            CellClass* cell;
berenger-bramas's avatar
berenger-bramas committed
319 320
            ContainerClass* targets;
            ContainerClass* sources;
321 322 323
        };
        LeafData* const leafsDataArray = new LeafData[this->leafsNumber];

324
        const int LeafIndex = OctreeHeight - 1;
325 326 327 328 329 330 331 332

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

        #pragma omp parallel
333
        {
334

335 336 337
            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)));
338
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
339

berenger-bramas's avatar
berenger-bramas committed
340
            typename OctreeClass::Iterator octreeIterator(tree);
341
            octreeIterator.gotoBottomLeft();
342 343 344 345 346

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

347
            // for each leafs
348
            for(int idxMyLeafs = start ; idxMyLeafs < end ; ++idxMyLeafs){
349
                //iterArray[leafs] = octreeIterator;
350
                //++leafs;
351
                const FTreeCoordinate& coord = octreeIterator.getCurrentGlobalCoordinate();
352
                const int shapePosition = (coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3);
353

354 355 356
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
357

358 359 360 361
                leafsDataArray[positionToWork].index = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell = octreeIterator.getCurrentCell();
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
362

363 364
                octreeIterator.moveRight();
            }
365

366 367
            #pragma omp barrier

berenger-bramas's avatar
berenger-bramas committed
368
            FDEBUG(if(!omp_get_thread_num()) computationCounter.tic());
369

berenger-bramas's avatar
berenger-bramas committed
370
            KernelClass& myThreadkernels = (*kernels[omp_get_thread_num()]);
371
            // There is a maximum of 26 neighbors
berenger-bramas's avatar
berenger-bramas committed
372
            ContainerClass* neighbors[26];
berenger-bramas's avatar
berenger-bramas committed
373
            MortonIndex neighborsIndex[26];
374
            int previous = 0;
375 376

            for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
377
                const int endAtThisShape = this->shapeLeaf[idxShape] + previous;
378

379
                #pragma omp for schedule(dynamic)
380 381 382
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
                    myThreadkernels.L2P(currentIter.cell, currentIter.targets);
383
                    // need the current particles and neighbors particles
384 385 386 387
                    FDEBUG(if(!omp_get_thread_num()) computationCounterP2P.tic());
                    const int counter = tree->getLeafsNeighborsWithIndex(neighbors, neighborsIndex, currentIter.index, LeafIndex);
                    myThreadkernels.P2P(currentIter.index, currentIter.targets, currentIter.sources , neighbors, neighborsIndex, counter);
                    FDEBUG(if(!omp_get_thread_num()) computationCounterP2P.tac());
388
                }
389 390

                previous = endAtThisShape;
391 392
            }
        }
393

394 395
        FDEBUG(computationCounter.tac());

396
        delete [] leafsDataArray;
397 398 399 400
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

401

402 403
        FDEBUG( FDebug::Controller << "\tFinished (@Direct Pass (L2P + P2P) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FDEBUG( FDebug::Controller << "\t\t Computation L2P + P2P : " << computationCounter.cumulated() << " s\n" );
404
        FDEBUG( FDebug::Controller << "\t\t Computation P2P : " << computationCounterP2P.cumulated() << " s\n" );
405
         
406 407 408 409 410 411 412
    }

};


#endif //FFMMALGORITHMTHREAD_HPP

413