FFmmAlgorithmThread.hpp 16.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// ===================================================================================
// Ce LOGICIEL "ScalFmm" est couvert par le copyright Inria 20xx-2012.
// Inria détient tous les droits de propriété sur le LOGICIEL, et souhaite que
// la communauté scientifique l'utilise afin de le tester et de l'évaluer.
// Inria donne gracieusement le droit d'utiliser ce LOGICIEL. Toute utilisation
// dans un but lucratif ou à des fins commerciales est interdite sauf autorisation
// expresse et préalable d'Inria.
// Toute utilisation hors des limites précisées ci-dessus et réalisée sans l'accord
// expresse préalable d'Inria constituerait donc le délit de contrefaçon.
// Le LOGICIEL étant un produit en cours de développement, Inria ne saurait assurer
// aucune responsabilité et notamment en aucune manière et en aucun cas, être tenu
// de répondre d'éventuels dommages directs ou indirects subits par l'utilisateur.
// Tout utilisateur du LOGICIEL s'engage à communiquer à Inria ses remarques
// relatives à l'usage du LOGICIEL
// ===================================================================================
16 17
#ifndef FFMMALGORITHMTHREAD_HPP
#define FFMMALGORITHMTHREAD_HPP
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

#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
44
* When using this algorithm the P2P is thread safe.
45
*/
berenger-bramas's avatar
berenger-bramas committed
46
template<class OctreeClass, class ParticleClass, class CellClass, class ContainerClass, class KernelClass, class LeafClass>
47
class FFmmAlgorithmThread : protected FAssertable{
berenger-bramas's avatar
berenger-bramas committed
48 49
    OctreeClass* const tree;                  //< The octree to work on
    KernelClass** kernels;                    //< The kernels
50

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

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

    const int MaxThreads;
58

59 60
    const int OctreeHeight;

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

71
        fassert(tree, "tree cannot be null", __LINE__, __FILE__);
72

berenger-bramas's avatar
berenger-bramas committed
73
        this->kernels = new KernelClass*[MaxThreads];
berenger-bramas's avatar
berenger-bramas committed
74
        for(int idxThread = 0 ; idxThread < MaxThreads ; ++idxThread){
berenger-bramas's avatar
berenger-bramas committed
75
            this->kernels[idxThread] = new KernelClass(*inKernels);
76 77
        }

berenger-bramas's avatar
berenger-bramas committed
78
        FDEBUG(FDebug::Controller << "FFmmAlgorithmThread (Max Thread " << omp_get_max_threads() << ")\n");
79 80 81 82
    }

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

    /**
      * To execute the fmm algorithm
      * Call this function to run the complete algorithm
      */
    void execute(){
94
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
95 96 97 98

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

        // 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 108 109
            const FTreeCoordinate& coord = octreeIterator.getCurrentCell()->getCoordinate();
            //const MortonIndex index = octreeIterator.getCurrentGlobalIndex();
            //coord.setPositionFromMorton(index, LeafIndex);
110 111 112
            ++this->shapeLeaf[(coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3)];

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

        bottomPass();
        upwardPass();

        downardPass();

        directPass();

        delete [] iterArray;
        iterArray = 0;

126
         
127 128
    }

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

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

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

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

162
        FDEBUG( FDebug::Controller << "\tFinished (@Bottom Pass (P2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
163
        FDEBUG( FDebug::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(){
173
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
174
        FDEBUG( FDebug::Controller.write("\tStart Upward Pass\n").write(FDebug::Flush); );
berenger-bramas's avatar
berenger-bramas committed
175 176
        FDEBUG(FTic counterTime);
        FDEBUG(FTic computationCounter);
177 178

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

        // for each levels
        for(int idxLevel = OctreeHeight - 2 ; idxLevel > 1 ; --idxLevel ){
186
            int numberOfCells = 0;
187 188
            // for each cells
            do{
189 190
                iterArray[numberOfCells] = octreeIterator;
                ++numberOfCells;
191 192 193 194 195
            } while(octreeIterator.moveRight());
            avoidGotoLeftIterator.moveUp();
            octreeIterator = avoidGotoLeftIterator;// equal octreeIterator.moveUp(); octreeIterator.gotoLeft();

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

207 208 209
            FDEBUG(computationCounter.tac());
        }

berenger-bramas's avatar
berenger-bramas committed
210

211
        FDEBUG( FDebug::Controller << "\tFinished (@Upward Pass (M2M) = "  << counterTime.tacAndElapsed() << "s)\n" );
berenger-bramas's avatar
berenger-bramas committed
212
        FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
213
         
214 215
    }

berenger-bramas's avatar
berenger-bramas committed
216 217 218 219
    /////////////////////////////////////////////////////////////////////////////
    // Downard
    /////////////////////////////////////////////////////////////////////////////

220 221
    /** M2L L2L */
    void downardPass(){
222
        FTRACE( FTrace::FFunction functionTrace(__FUNCTION__, "Fmm" , __FILE__ , __LINE__) );
223 224

        { // first M2L
berenger-bramas's avatar
berenger-bramas committed
225 226 227 228
            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
229
            typename OctreeClass::Iterator octreeIterator(tree);
230
            octreeIterator.moveDown();
berenger-bramas's avatar
berenger-bramas committed
231
            typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
232 233 234

            // for each levels
            for(int idxLevel = 2 ; idxLevel < OctreeHeight ; ++idxLevel ){
235
                int numberOfCells = 0;
236 237
                // for each cells
                do{
238 239
                    iterArray[numberOfCells] = octreeIterator;
                    ++numberOfCells;
240 241 242 243 244
                } while(octreeIterator.moveRight());
                avoidGotoLeftIterator.moveDown();
                octreeIterator = avoidGotoLeftIterator;

                FDEBUG(computationCounter.tic());
berenger-bramas's avatar
berenger-bramas committed
245
                #pragma omp parallel
246
                {
berenger-bramas's avatar
berenger-bramas committed
247
                    KernelClass * const myThreadkernels = kernels[omp_get_thread_num()];
248
                    const CellClass* neighbors[189];
249

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

259
            FDEBUG( FDebug::Controller << "\tFinished (@Downward Pass (M2L) = "  << counterTime.tacAndElapsed() << "s)\n" );
berenger-bramas's avatar
berenger-bramas committed
260
            FDEBUG( FDebug::Controller << "\t\t Computation : " << computationCounter.cumulated() << " s\n" );
261 262 263
        }

        { // second L2L
berenger-bramas's avatar
berenger-bramas committed
264 265 266 267
            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
268
            typename OctreeClass::Iterator octreeIterator(tree);
269 270
            octreeIterator.moveDown();

berenger-bramas's avatar
berenger-bramas committed
271
            typename OctreeClass::Iterator avoidGotoLeftIterator(octreeIterator);
272 273 274 275

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

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

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

301
         
302 303
    }

berenger-bramas's avatar
berenger-bramas committed
304 305 306 307
    /////////////////////////////////////////////////////////////////////////////
    // Direct
    /////////////////////////////////////////////////////////////////////////////

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

316
        omp_lock_t lockShape[SizeShape];
317
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
318
            omp_init_lock(&lockShape[idxShape]);
319 320
        }

321 322 323
        struct LeafData{
            MortonIndex index;
            CellClass* cell;
berenger-bramas's avatar
berenger-bramas committed
324 325
            ContainerClass* targets;
            ContainerClass* sources;
326 327 328
        };
        LeafData* const leafsDataArray = new LeafData[this->leafsNumber];

329
        const int LeafIndex = OctreeHeight - 1;
330 331 332 333 334 335 336 337

        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
338
        {
339

340 341 342
            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)));
343
            const int end = (tempEnd > this->leafsNumber ? this->leafsNumber : tempEnd);
344

berenger-bramas's avatar
berenger-bramas committed
345
            typename OctreeClass::Iterator octreeIterator(tree);
346
            octreeIterator.gotoBottomLeft();
347 348 349 350 351

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

352
            // for each leafs
353
            for(int idxMyLeafs = start ; idxMyLeafs < end ; ++idxMyLeafs){
354
                //iterArray[leafs] = octreeIterator;
355
                //++leafs;
356
                const FTreeCoordinate& coord = octreeIterator.getCurrentGlobalCoordinate();
357
                const int shapePosition = (coord.getX()%3)*9 + (coord.getY()%3)*3 + (coord.getZ()%3);
358

359 360 361
                omp_set_lock(&lockShape[shapePosition]);
                const int positionToWork = startPosAtShape[shapePosition]++;
                omp_unset_lock(&lockShape[shapePosition]);
362

363 364 365 366
                leafsDataArray[positionToWork].index = octreeIterator.getCurrentGlobalIndex();
                leafsDataArray[positionToWork].cell = octreeIterator.getCurrentCell();
                leafsDataArray[positionToWork].targets = octreeIterator.getCurrentListTargets();
                leafsDataArray[positionToWork].sources = octreeIterator.getCurrentListSrc();
367

368 369
                octreeIterator.moveRight();
            }
370

371 372
            #pragma omp barrier

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

berenger-bramas's avatar
berenger-bramas committed
375
            KernelClass& myThreadkernels = (*kernels[omp_get_thread_num()]);
376
            // There is a maximum of 26 neighbors
berenger-bramas's avatar
berenger-bramas committed
377
            ContainerClass* neighbors[26];
berenger-bramas's avatar
berenger-bramas committed
378
            MortonIndex neighborsIndex[26];
379
            int previous = 0;
380 381

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

384
                #pragma omp for schedule(dynamic)
385 386 387
                for(int idxLeafs = previous ; idxLeafs < endAtThisShape ; ++idxLeafs){
                    LeafData& currentIter = leafsDataArray[idxLeafs];
                    myThreadkernels.L2P(currentIter.cell, currentIter.targets);
388
                    // need the current particles and neighbors particles
389 390 391 392
                    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());
393
                }
394 395

                previous = endAtThisShape;
396 397
            }
        }
398

399 400
        FDEBUG(computationCounter.tac());

401
        delete [] leafsDataArray;
402 403 404 405
        for(int idxShape = 0 ; idxShape < SizeShape ; ++idxShape){
            omp_destroy_lock(&lockShape[idxShape]);
        }

406

407 408
        FDEBUG( FDebug::Controller << "\tFinished (@Direct Pass (L2P + P2P) = "  << counterTime.tacAndElapsed() << "s)\n" );
        FDEBUG( FDebug::Controller << "\t\t Computation L2P + P2P : " << computationCounter.cumulated() << " s\n" );
409
        FDEBUG( FDebug::Controller << "\t\t Computation P2P : " << computationCounterP2P.cumulated() << " s\n" );
410
         
411 412 413 414 415 416 417
    }

};


#endif //FFMMALGORITHMTHREAD_HPP

418